?? 索引器.txt
字號:
索引器聲明
索引器使您得以按照與數(shù)組相同的方式為類或結(jié)構(gòu)實例建立索引。若要聲明索引器,請使用以下方式:
示例
以下示例說明如何聲明私有數(shù)組字段、myArray 和索引器。通過使用索引器可直接訪問實例 b[i]。另一種使用索引器的方法是將數(shù)組聲明為 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
注意,當(dāng)計算索引器的訪問時(例如,在 Console.Write 語句中),調(diào)用 get 訪問器。因此,如果 get 訪問器不存在,將發(fā)生編譯時錯誤。
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -