首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# List 字串索引器:擴充方法不支援,需自訂類別繼承

     編輯:程式設計綜合問答

直接回答

擴充方法無法定義索引器(this[]),C# 語法限制。若需 list["key"] 語法,必須自訂類別繼承 List<T> 並定義索引器。

實作範例

public class KeyedList : List where T : IKeyed {
    public T this[string key] {
        get => this.FirstOrDefault(x => x.Key == key);
        set {
            var idx = this.FindIndex(x => x.Key == key);
            if (idx >= 0) this[idx] = value;
            else this.Add(value);
        }
    }
}

public interface IKeyed {
    string Key { get; }
}

public class Room : IKeyed {
    public string RoomNo { get; set; }
    public string Key => RoomNo; // 以 RoomNo 為鍵
}

使用方式

var rooms = new KeyedList();
rooms.Add(new Room { RoomNo = "101" });
Room r = rooms["101"]; // 直接用字串索引

替代方案

  • Dictionary<string, T>:原生支援字串鍵,查找 O(1),但無序。
  • LINQ 擴充方法:list.FirstOrDefault(x => x.RoomNo == "101"),語意清晰無需新類別。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved