C# 編程指南使用索引器(C# 編程指南)
索引器允許您按照處理數組的方式索引類、結構或介面。有關對介面使用索引器的更多資訊,請參見介面索引器。
要聲明類或結構上的索引器,請使用 this 關鍵字,如下例所示:
複製代碼
public int this[int index] // Indexer declaration{// get and set accessors}
備忘
索引器類型及其參數類型必須至少如同索引器本身一樣是可訪問的。有關可存取層級的更多資訊,請參見存取修飾詞。
索引器的簽名由其形參的數量和類型組成。它不包括索引器類型或形參名。如果在同一類中聲明一個以上的索引器,則它們必須具有不同的簽名。
索引器值不歸類為變數;因此,不能將索引器值作為 ref 或 out 參數來傳遞。
要為索引器提供一個其他語言可以使用的名字,請使用聲明中的 name 屬性。例如:
複製代碼
[System.Runtime.CompilerServices.IndexerName("TheItem")]public int this [int index] // Indexer declaration{}
此索引器將具有名稱 TheItem。不提供名稱屬性將產生 Item 預設名稱。
樣本 1
下面的樣本說明如何聲明私人數組欄位、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]);}}}
輸出
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 訪問器不存在,將發生編譯時間錯誤。
使用其他值進行索引
C# 並不將索引類型限制為整數。例如,對索引器使用字串可能是有用的。通過搜尋集合內的字串並返回相應的值,可以實現此類的索引器。由於訪問器可被重載,字串和整數版本可以共存。
樣本 2
在此例中,聲明了儲存星期幾的類。聲明了一個 get 訪問器,它接受字串(天名稱),並返回相應的整數。例如,星期日將返回 0,星期一將返回 1,等等。
C# 複製代碼
// Using a string as an indexer valueclass DayCollection{string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };// This method finds the day or returns -1private int GetDay(string testDay){int i = 0;foreach (string day in days){if (day == testDay){return i;}i++;}return -1;}// The get accessor returns an integer for a given stringpublic int this[string day]{get{return (GetDay(day));}}}class Program{static void Main(string[] args){DayCollection week = new DayCollection();System.Console.WriteLine(week["Fri"]);System.Console.WriteLine(week["Made-up Day"]);}}
輸出
5
-1
可靠編程
提高索引器的安全性和可靠性有兩種主要的方法: