同一組資料常需支援多種查詢鍵(如城市 ID、拼音縮寫、名稱枚舉)。本文示範透過索引器多載,讓用戶端依上下文自然選擇鍵型別,免記憶方法名。
public enum CityName { Taipei, Taichung, Kaohsiung }
public class WeatherService
{
private Dictionary _byId = new();
private Dictionary _byPinyin = new();
private Dictionary _byEnum = new();
// 依城市 ID 查詢
public CityTemp this[int cityId]
{
get => _byId.TryGetValue(cityId, out var t) ? t : null;
}
// 依拼音縮寫查詢
public CityTemp this[string pinyin]
{
get => _byPinyin.TryGetValue(pinyin, out var t) ? t : null;
}
// 依枚舉查詢
public CityTemp this[CityName name]
{
get => _byEnum.TryGetValue(name, out var t) ? t : null;
}
}
var svc = new WeatherService();
// 初始化資料...
var t1 = svc[1001]; // ID
var t2 = svc["taipei"]; // 拼音
var t3 = svc[CityName.Taipei]; // 枚舉
public class MultiKeyIndex
{
private Dictionary _dict = new();
public TValue this[TKey key] => _dict.TryGetValue(key, out var v) ? v : default;
public void Add(TKey key, TValue value) => _dict[key] = value;
public bool Remove(TKey key) => _dict.Remove(key);
}
public class WeatherService
{
private MultiKeyIndex _byId = new();
private MultiKeyIndex _byPinyin = new();
private MultiKeyIndex _byEnum = new();
public CityTemp this[int id] => _byId[id];
public CityTemp this[string pinyin] => _byPinyin[pinyin];
public CityTemp this[CityName name] => _byEnum[name];
}
索引器多載讓多重檢索路徑以統一語法呈現,大幅降低用戶端認知負荷。配合泛型輔助類別,程式碼更精簡、可維護。