经常见有这样的类:如aClass a = new Class();然后在程序里出现个a[i]="some string";感觉好奇怪:既然没有声明类数组却用[]索引,而且返回个string类型,在msdn2和google、baidu同学的帮助之下终于弄明白原来是c#的索引器,弄明白了原理之后自己写了个小示例程序。声明:程序完全自主编写,只要对大家有帮助,随便拷贝: )
using System ;
/// <summary>
/// 索引器示例
/// </summary>
class StringCollection //建立一个字符串容器类
{
readonly int _count;
string[] str;
public StringCollection(int count)
{
if (count > 1)
{
_count = count;
str = new string[_count];
}
}
public string this[int index] //索引器
{
get
{
if (index >= 0 && index < _count)
return str[index];
else
return "error index!";
}
set
{
if (index < 0 || index >= _count)
throw new Exception("Out of Range!");
else
str[index] = value;
}
}
static void Main()
{
StringCollection test = new StringCollection(5);
test[0] = "Hello Word!";
test[2] = "Hi China!";
test[4] = "How do you do!";
for (int i = 0; i < 6; i++)
Console.WriteLine("String #{0} = {1}", i, test[i]);
StringCollection[] a = new StringCollection[3]; //定义一个3维StringCollection
for (int i =0;i<3;i++)
for (int j = 0; j < 2; j++)
{
a[i] = new StringCollection(2); //对每一个StringCollection调用构造函数
a[i][j] = i.ToString() + j.ToString();
Console.WriteLine(a[i][j]);
}
Console.Read();
}
}