📄 索引器.txt
字号:
索引器声明
索引器使您得以按照与数组相同的方式为类或结构实例建立索引。若要声明索引器,请使用以下方式:
示例
以下示例说明如何声明私有数组字段、myArray 和索引器。通过使用索引器可直接访问实例 b[i]。另一种使用索引器的方法是将数组声明为 public 成员并直接访问它的成员 myArray[i]。
// cs_keyword_indexers.cs
using System;
class IndexerClass
{
private int [] myArray = new int[100];
public int this [int index] // Indexer declaration
{
get
{
// Check the index limits.
if (index < 0 || index >= 100)
return 0;
else
return myArray[index];
}
set
{
if (!(index < 0 || index >= 100))
myArray[index] = value;
}
}
}
public class MainClass
{
public static void Main()
{
IndexerClass b = new IndexerClass();
// Call the indexer to initialize the elements #3 and #5.
b[3] = 256;
b[5] = 1024;
for (int i=0; i<=10; i++)
{
Console.WriteLine("Element #{0} = {1}", i, b[i]);
}
}
}
输出
Element #0 = 0
Element #1 = 0
Element #2 = 0
Element #3 = 256
Element #4 = 0
Element #5 = 1024
Element #6 = 0
Element #7 = 0
Element #8 = 0
Element #9 = 0
Element #10 = 0
注意,当计算索引器的访问时(例如,在 Console.Write 语句中),调用 get 访问器。因此,如果 get 访问器不存在,将发生编译时错误。
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -