索引器是特殊的屬性,讓類別實例支援陣列語法 obj[index]。它使用 this 關鍵字而非名稱,參數置於方括號內。適用於集合類別、大型資料存取、資源封裝等場景。
class Sample
{
// 唯讀索引器
public string this[int index]
{
get => $"You passed {index}";
}
// 讀寫索引器
private string[] data = new string[10];
public string this[int index]
{
get => data[index];
set => data[index] = value;
}
}
// 使用
var s = new Sample();
Console.WriteLine(s[55]); // 呼叫 get
s[0] = "Hello"; // 呼叫 set
| 特性 | 屬性 | 索引器 |
|---|---|---|
| 識別方式 | 唯一名稱 | 唯一簽章(參數型別/個數),支援多載 |
| 靜態性 | 可為 static | 必須為實例成員 |
| 存取子參數 | 無參數 | 可存取索引參數 |
參數型別不限於 int,可為 string、enum 等,並支援多參數:
public class Matrix
{
private double[,] data = new double[10, 10];
// 兩個整數參數
public double this[int row, int col]
{
get => data[row, col];
set => data[row, col] = value;
}
// 字串參數:依名稱查找
public double this[string name]
{
get => name switch { "trace" => Trace(), _ => 0 };
}
private double Trace() { /* ... */ return 0; }
}
介面只宣告存取子,不加存取修飾詞:
interface IStringIndexer
{
string this[int index] { get; set; }
}
class MyClass : IStringIndexer
{
private string[] arr = new string[100];
public string this[int index]
{
get => arr[index];
set => arr[index] = value;
}
}
IList<T>、IDictionary<TKey, TValue> 皆定義索引器,統一集合存取介面。
IndexOutOfRangeException 或回傳預設值(依語意)。get_Item/set_Item 方法,內聯後開銷極低。GetById、Add)更明確。