C#中索引器小解

索引器允许按照数组的额方式索引对象的数组元素,索引器可以使用户像访问数组一样访问类成员,索引器类似于属性,不同之处在于它们的访问器采用参数。
例:
class IndexerClass
{
//定义数组
private int[] arr = new int[100];
//定义索引器
public int this[int index] // Indexer declaration
{
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++)
{
System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
}
}
}
posted @ 2009-07-10 15:36  think_fish  Views(121)  Comments(0Edit  收藏  举报