阅读量:0
在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>
实例,并向其添加了两个键值对。最后,我们通过键从字典中检索值并将其输出到控制台。