索引器讓類別的實例可以使用陣列語法 [] 來存取內部資料。它類似屬性,但不需要名稱,改用 this 關鍵字,並接受索引參數。簡單說,索引器讓物件「看起來像陣列」。
public 回傳型別 this[參數型別 索引名稱]
{
get
{
// 根據索引回傳值
return 某個值;
}
set
{
// 根據索引與 value 設定內部資料
}
}
以下 SpellingList 類別內部用字串陣列儲存單字,透過索引器對外暴露:
using System;
public class SpellingList
{
protected string[] words = new string[size];
static public int size = 10;
public SpellingList()
{
for (int x = 0; x < size; x++)
words[x] = String.Format("Word{0}", x);
}
public string this[int index]
{
get
{
string tmp;
if (index >= 0 && index <= size - 1)
tmp = words[index];
else
tmp = "";
return tmp;
}
set
{
if (index >= 0 && index <= size - 1)
words[index] = value;
}
}
}
public class TestApp
{
public static void Main()
{
SpellingList myList = new SpellingList();
myList[3] = "=====";
myList[4] = "Brad";
myList[5] = "was";
myList[6] = "Here!";
myList[7] = "=====";
for (int x = 0; x < SpellingList.size; x++)
Console.WriteLine(myList[x]);
}
}
Word0
Word1
Word2
=====
Brad
was
Here!
=====
Word8
Word9
Word0~Word9。public string this[int index] 宣告索引器,回傳 string。value。myList[3] = "=====" 直接呼叫 set;Console.WriteLine(myList[x]) 呼叫 get。當它能讓程式碼更易讀、更直觀時。例如實作堆疊、佇列、自訂集合,或封裝大型檔案、有限資源的存取邏輯。避免濫用:若語意不明確,寧可用具名方法。