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();
}
}