索引器讓類或結構體像陣列一樣通過下標訪問內部數據,語法形式為 this[參數列表]。它是「屬性」的參數化泛化,本質是 get/set 訪問器的語法糖。
public class SampleCollection
{
private T[] _items = new T[100];
// 索引器聲明
public T this[int index]
{
get => _items[index];
set => _items[index] = value;
}
}
| 特性 | 說明 | 示例 |
|---|---|---|
| 語法糖 | 編譯為 get_Item/set_Item 方法 | IL 可見 get_Item(Int32) |
| this 關鍵字 | 標識索引器,非實例引用 | this[int i] |
| value 隱式參數 | set 訪問器自動可用 | set { _arr[i] = value; } |
| 參數靈活 | 可為任意類型、多參數 | this[string key]、this[int x, int y] |
| 支援重載 | 同類多個索引器,參數簽名不同 | 按 int 索引 / 按 string 鍵 並存 |
| 可多維 | 模擬多維陣列/矩陣訪問 | matrix[x, y] |
| 介面實現 | 介面可聲明索引器,類實現隱式/顯式 | interface IRepo { T this[string id] { get; } } |
public class ConfigStore
{
private readonly Dictionary _data = new Dictionary();
public string this[string key]
{
get => _data.TryGetValue(key, out var v) ? v : null;
set => _data[key] = value ?? throw new ArgumentNullException(nameof(value));
}
// 唯讀索引器(僅 get)
public string this[string key, bool readOnly]
{
get => this[key];
}
}
public class Matrix
{
private readonly T[,] _grid;
public int Rows { get; }
public int Cols { get; }
public Matrix(int rows, int cols)
{
Rows = rows; Cols = cols;
_grid = new T[rows, cols];
}
public T this[int row, int col]
{
get
{
Validate(row, col);
return _grid[row, col];
}
set
{
Validate(row, col);
_grid[row, col] = value;
}
}
private void Validate(int r, int c)
{
if (r < 0 || r >= Rows || c < 0 || c >= Cols)
throw new IndexOutOfRangeException($"({r},{c}) 超出範圍 [{Rows}x{Cols}]");
}
}
public interface IRepository
{
T this[string id] { get; set; }
IEnumerable All { get; }
}
public class UserRepository : IRepository
{
private readonly Dictionary _users = new Dictionary();
// 隱式實現
public User this[string id]
{
get => _users.TryGetValue(id, out var u) ? u : null;
set => _users[id] = value;
}
public IEnumerable All => _users.Values;
}
public class ReadOnlyList
{
private readonly T[] _items;
public ReadOnlyList(params T[] items) => _items = items;
public T this[int i] => _items[i]; // 僅 get
public int Count => _items.Length;
}
| 維度 | 屬性 | 索引器 | 方法 |
|---|---|---|---|
| 參數 | 無 | 有(至少一個) | 任意 |
| 調用語法 | obj.Prop | obj[index] | obj.Method(arg) |
| 適用場景 | 單一值特徵 | 集合/映射訪問 | 行為/計算/副作用 |
| 重載 | 不可 | 可 | 可 |
| 介面聲明 | 可 | 可 | 可 |
IndexOutOfRangeException 或 ArgumentOutOfRangeExceptionthis[int row, int column] 而非 this[int a, int b]bool TryGet(int index, out T value) 避免異常開銷/// 零基索引 明確語義List<T>[int] — 基礎陣列訪問Dictionary<TKey,TValue>[TKey] — 鍵值映射,set 覆蓋/添加,get 不存在拋異常DataTable.Rows[int] — 行集合訪問返回 DataRowConfigurationManager.AppSettings[string] — 配置讀取HttpContext.Current.Items[object] — 請求級數據槽索引器是 .NET 類庫設計中賦予類型「集合語義」的關鍵機制。合理運用重載、多維、介面實現等高級特性,能讓自定義類型擁有如原生陣列、字典般直觀的使用體驗。記住:索引器本質是帶參數的屬性,設計時遵循屬性的純粹性原則。