C# 编程指南
使用索引器(C# 编程指南)
索引器允许您按照处理数组的方式索引类、结构或接口。有关对接口使用索引器的更多信息,请参见接口索引器。
要声明类或结构上的索引器,请使用 this 关键字,如下例所示:
public int this[int index] // Indexer declaration
{
// get and set accessors
}
下面的示例说明如何声明私有数组字段、arr 和索引器。使用索引器可直接访问实例 test[i]。另一种使用索引器的方法是将数组声明为 public 成员并直接访问它的成员 arr[i]。
C#
class IndexerClass
{
private int[] arr = new int[100];
public int this[int index] // Indexer declaration
{
get
{
// Check the index limits.
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();
// Call the indexer to initialize the elements #3 and #5.
test[3] = 256;
test[5] = 1024;
for (int i = 0; i <= 10; i++)
{
System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
}
}
}