索引器不限於一維陣列,可封裝多維陣列、空間資料、樹/圖結構、多因子計算結果。本文以法定節日資訊查詢為例,展示類 DateTimePicker 的直觀存取體驗。
public class GregorianCalendarFixture
{
private Dictionary _holidays = new();
public GregorianCalendarFixture()
{
// 初始化固定節日
_holidays[new DateTime(1, 1, 1)] = new HolidayInfo("元旦", HolidayType.National);
_holidays[new DateTime(1, 2, 14)] = new HolidayInfo("情人節", HolidayType.Observance);
// ... 更多節日
}
// 依日期查詢(支援年份忽略)
public HolidayInfo this[DateTime date]
{
get
{
var key = new DateTime(1, date.Month, date.Day); // 正規化至元年
return _holidays.TryGetValue(key, out var info) ? info : null;
}
}
// 依月、日查詢
public HolidayInfo this[int month, int day]
{
get => this[new DateTime(1, month, day)];
}
// 依節日名稱查詢(反向索引)
public IEnumerable this[string holidayName]
{
get => _holidays.Where(kv => kv.Value.Name == holidayName).Select(kv => kv.Key);
}
}
var cal = new GregorianCalendarFixture();
var today = cal[DateTime.Today]; // 今天是否為節日
var newYear = cal[1, 1]; // 1月1日
var valentineDates = cal["情人節"]; // 所有情人節日期
| 資料類型 | 索引器參數設計 |
|---|---|
多維陣列 T[,] | this[int x, int y] |
| 空間資料 (2D/3D/4D) | this[int x, int y, int z] 或 this[Vector3 pos] |
| 樹狀結構 | this[string path] (如 \"root/child/leaf\") |
| 圖/語義網路 | this[NodeId from, NodeId to] 取得邊權重 |
| 多因子計算結果 | this[FactorA a, FactorB b, FactorC c] |
x, y, z、row, col)。null 或拋出 ArgumentOutOfRangeException,文件化行為。索引器是封裝複雜資料存取邏輯的利器。善用多參數、多載、泛型輔助,能讓任何資料結構呈現陣列般直觀的存取介面。