索引器讓對象像數組一樣通過 [] 訪問,賦予類「虛擬數組」行為。語法類似屬性但使用 this 關鍵字。
public elementType this[int index] {
get { return internalArray[index]; }
set { internalArray[index] = value; }
}
class IndexedNames {
private string[] names = new string[10];
public IndexedNames() { for (int i=0;i<10;i++) names[i]="N.A."; }
public string this[int index] {
get { return (index>=0 && index<10) ? names[index] : ""; }
set { if (index>=0 && index<10) names[index] = value; }
}
public int this[string name] { // 重載:字符串參數
get { for (int i=0;i<10;i++) if (names[i]==name) return i; return -1; }
}
}
// 使用
var names = new IndexedNames();
names[0] = "Zara"; names[1] = "Riz";
Console.WriteLine(names[0]); // Zara
Console.WriteLine(names["Riz"]); // 1
this 代表實例int、string、int,int)索引器讓集合類、矩陣、查找表等數據結構 API 更直觀自然。