C# 编程指南
使用索引器(C# 编程指南)

索引器允许您按照处理数组的方式索引结构接口。有关对接口使用索引器的更多信息,请参见接口索引器

要声明类或结构上的索引器,请使用 this 关键字,如下例所示:

public int this[int index]    // Indexer declaration
{
// get and set accessors
}

索引器类型及其参数类型必须至少如同索引器本身一样是可访问的。有关可访问级别的更多信息,请参见访问修饰符

索引器的签名由其形参的数量和类型组成。它不包括索引器类型或形参名。如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。

索引器值不归类为变量;因此,不能将索引器值作为 refout 参数来传递。

要为索引器提供一个其他语言可以使用的名字,请使用声明中的 name 属性。例如:

此索引器将具有名称 TheItem。不提供名称属性将生成 Item 默认名称。

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

相关文章:

  • 2021-05-19
  • 2021-05-21
  • 2022-01-29
  • 2022-01-28
  • 2021-07-08
  • 2021-11-17
  • 2021-07-05
猜你喜欢
  • 2022-12-23
  • 2021-11-23
  • 2021-12-17
  • 2022-01-05
  • 2021-07-27
  • 2022-12-23
  • 2021-10-23
相关资源
相似解决方案