索引器
看看msdn
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
public int this[int index]
{
get {}
set {}
}
using System;
class IndexerClass
{
private int[] arr = new int[100];
public int this[int index]
{
get
{
if (index < 0 || index >= 100)
{
return 0;
}
else
{
return arr[index];
}
}
set
{
if (!(index < 0 || index >= 100))
{
arr[index] = value;
}
}
}
}
class MainClass
{
static void Main()
{
IndexerClass test = new IndexerClass();
test[3] = 256;
test[5] = 1024;
for (int i = 0; i <= 10; i++)
{
Console.WriteLine("Element {0} = {1}", i, test[i]);
}
}
}