2016-03-31 57 views
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函數而不是覆蓋函數。

對這個問題有什麼想法?

+5

在你的例子中,超類和子類都拋出一個沒有實例化的異常 –

回答

0

Hmmmmm, - 所有的函數調用:

throw new NotImplementedException(); 

這就是爲什麼他們拋出一個NotImplementedException ...

我只是想在子類中實現的一些明智的代碼和它的作品。

public override bool Equals(SuperClass dictKeyComparerA, SuperClass dictKeyComparerB) 
{ 
    var a = dictKeyComparerA as SubClass; 
    var b = dictKeyComparerB as SubClass; 
    return a.application == b.application; 
} 

public override int GetHashCode(SuperClass dictKeyComparer) 
{ 
    return application.GetHashCode(); 
}