0
我想實現一個子類的IEqualityComparer,它將被存儲爲字典的關鍵字。IEqualityComparer不在字典中調用子類
以下是我
public class SuperClass : IEqualityComparer<SuperClass> {
public virtual bool Equals(SuperClass dictKeyComparerA, SuperClass dictKeyComparerB) {
throw new NotImplementedException();
}
public virtual int GetHashCode(SuperClass dictKeyComparer) {
throw new NotImplementedException();
}
}
public class SubClass : SuperClass {
private readonly string application;
public SubClass(string application) {
this.application = application;
}
public override bool Equals(SuperClass dictKeyComparerA, SuperClass dictKeyComparerB) {
throw new NotImplementedException();
}
public override int GetHashCode(SuperClass dictKeyComparer) {
throw new NotImplementedException();
}
}
和我有以下嘗試搜索詞典:
Dictionary<SubClass, List<string>> TestDict3 = new Dictionary<SubClass, List<string>>(new SubClass("random"));
var testKeyb = new SubClass("12345");
var testListb = new List<string>{"aaaaa"};
TestDict3.Add(testKeyb, testListb);
var testKey2b = new SubClass("12345");
var testKey3b = new SubClass("56973");
if(TestDict3.ContainsKey(testKey2b)) {
Console.WriteLine("found testKey2b");
}
else {
Console.WriteLine("did not found testKey2b");
}
if(TestDict3.ContainsKey(testKey3b)) {
Console.WriteLine("found testKey3b");
}
else {
Console.WriteLine("did not found testKey3b");
}
當代碼運行,它返回一個未實現的例外,因爲它正在調用超類GetHashCode函數而不是覆蓋函數。
對這個問題有什麼想法?
在你的例子中,超類和子類都拋出一個沒有實例化的異常 –