首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 索引器進階應用(三):多重檢索路徑與索引器多載

     編輯:關於C語言

前言

同一組資料常需支援多種查詢鍵(如城市 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]; // 枚舉

設計要點

  1. 參數型別唯一:每個索引器參數型別必須不同,否則編譯器無法區分多載。
  2. 內部資料結構分離:為每種鍵維護獨立字典,查詢 O(1)。
  3. 同步更新:新增/刪除資料時,需同步更新所有字典。
  4. 回傳型別一致:所有多載回傳相同型別(或共同基類/介面),保持 API 一致性。

進階:泛型索引器輔助類別


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];
}

結語

索引器多載讓多重檢索路徑以統一語法呈現,大幅降低用戶端認知負荷。配合泛型輔助類別,程式碼更精簡、可維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved