在C#中,要自定義字典的鍵類型,您需要?jiǎng)?chuàng)建一個(gè)自定義類并實(shí)現(xiàn)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
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)名為CustomKey
的自定義類,它包含兩個(gè)屬性:KeyPart1
(字符串類型)和KeyPart2
(整數(shù)類型)。我們實(shí)現(xiàn)了IEquatable<CustomKey>
接口的Equals
方法來(lái)比較兩個(gè)CustomKey
對(duì)象是否相等,同時(shí)重寫(xiě)了GetHashCode
方法以確保字典可以正確地存儲(chǔ)和檢索鍵值對(duì)。
然后,在Main
方法中,我們創(chuàng)建了一個(gè)Dictionary<CustomKey, string>
實(shí)例,并向其添加了兩個(gè)鍵值對(duì)。最后,我們通過(guò)鍵從字典中檢索值并將其輸出到控制臺(tái)。