在C#中,要自定義字典的鍵類型,您需要創建一個自定義類并實現IEquatable<T>
接口
using System;
using System.Collections.Generic;
public class CustomKey : IEquatable<CustomKey>
{
public string KeyPart1 { get; set; }
public int KeyPart2 { get; set; }
public bool Equals(CustomKey other)
{
if (other == null) return false;
return this.KeyPart1 == other.KeyPart1 && this.KeyPart2 == other.KeyPart2;
}
public override bool Equals(object obj)
{
return Equals(obj as CustomKey);
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + (KeyPart1 != null ? KeyPart1.GetHashCode() : 0);
hash = hash * 23 + KeyPart2.GetHashCode();
return hash;
}
}
}
class Program
{
static void Main(string[] args)
{
var customDict = new Dictionary<CustomKey, string>();
var key1 = new CustomKey { KeyPart1 = "A", KeyPart2 = 1 };
var key2 = new CustomKey { KeyPart1 = "B", KeyPart2 = 2 };
customDict[key1] = "Value1";
customDict[key2] = "Value2";
Console.WriteLine(customDict[key1]); // Output: Value1
Console.WriteLine(customDict[key2]); // Output: Value2
}
}
在這個示例中,我們創建了一個名為CustomKey
的自定義類,它包含兩個屬性:KeyPart1
(字符串類型)和KeyPart2
(整數類型)。我們實現了IEquatable<CustomKey>
接口的Equals
方法來比較兩個CustomKey
對象是否相等,同時重寫了GetHashCode
方法以確保字典可以正確地存儲和檢索鍵值對。
然后,在Main
方法中,我們創建了一個Dictionary<CustomKey, string>
實例,并向其添加了兩個鍵值對。最后,我們通過鍵從字典中檢索值并將其輸出到控制臺。