C#中的多鍵字典
C#本身不支援多鍵字典這種資料結構。然而,一些開源庫提供了此功能。
基於元組的實作
常見方法是使用元組作為鍵。元組是一種資料結構,它表示多個值的集合,每個值都有自己的類型。例如,以下程式碼定義了一個包含兩個鍵(一個字串和一個整數)的元組:
var tuple = (key1: "key1", key2: 1);
然後,您可以將元組用作字典的鍵:
var dictionary = new Dictionary<Tuple<string, int>, string>(); dictionary.Add(tuple, "value");
基於結構體的實現
另一個選擇是定義一個自訂結構體來表示多鍵值。以下程式碼定義了一個包含兩個欄位的結構體:
public struct Key { public string Key1 { get; set; } public int Key2 { get; set; } }
然後,您可以將結構體用作字典的鍵:
var dictionary = new Dictionary<Key, string>(); dictionary.Add(new Key { Key1 = "key1", Key2 = 1 }, "value");
值物件實作
一種更複雜的方法是定義一個類別來封裝多個值並強制執行值語義。這種方法提供了一種簡潔且易於維護的方式來處理多鍵資料。以下程式碼定義了一個包含兩個欄位的值物件:
public class ValueObject { public string Key1 { get; private set; } public int Key2 { get; private set; } public ValueObject(string key1, int key2) { Key1 = key1; Key2 = key2; } public override bool Equals(object obj) { return obj is ValueObject other && other.Key1 == Key1 && other.Key2 == Key2; } public override int GetHashCode() { return HashCode.Combine(Key1, Key2); } }
然後,您可以將值物件用作字典的鍵:
var dictionary = new Dictionary<ValueObject, string>(); dictionary.Add(new ValueObject("key1", 1), "value");
以上是如何用C#實作多鍵字典?的詳細內容。更多資訊請關注PHP中文網其他相關文章!