索引子讓類別實例支援 obj[index] 語法存取內部集合/資料。本質是帶參數的屬性,使用 this 關鍵字定義。
class DataSeries
{
private float[] _data = { 1.1f, 2.2f, 3.3f };
public int Length
{
get => _data.Length;
set => Array.Resize(ref _data, value);
}
// 索引子
public float this[int index]
{
get => _data[index];
set => _data[index] = value;
}
}
// 使用
var ds = new DataSeries();
Console.WriteLine(ds[0]); // 1.1
ds[1] = 9.9f;
Console.WriteLine(ds[1]); // 9.9
string、enum、多參數。get/set 可個別設定 (如 public get; private set;)。class Matrix
{
private double[,] _m = new double[3,3];
public double this[int row, int col]
{
get => _m[row, col];
set => _m[row, col] = value;
}
}
class WeekWeather
{
public string this[string day] // 字串索引
{
get => day switch
{
"Monday" => "Rainy",
"Friday" => "Sunny",
_ => "Cloudy"
};
}
}
interface IRepository<T>
{
T this[int id] { get; set; }
}
class UserRepository : IRepository<User>
{
private Dictionary<int, User> _db = new();
public User this[int id]
{
get => _db.TryGetValue(id, out var u) ? u : null;
set => _db[id] = value;
}
}
| 場景 | 索引子設計 |
|---|---|
| 資料表列存取 | row["ColumnName"] (DataRow 風格) |
| 多維陣列/矩陣 | matrix[row, col] |
| 快取/字典包裝 | cache[key] 附加過期/統計邏輯 |
| 位元操作 | bits[index] 獲取/設定特定位 |
| 動態物件 | 搭配 DynamicObject 實作動態索引 |
GetValue(key))。索引子提供直觀的集合存取語法,是建構領域特定語言 (DSL) 風格 API 的利器。善用多載、介面定義與非 int 參數,能大幅提升 API 表達力。