2014-10-16 37 views
2

我是C#的新手,我試圖爲字典創建自定義密鑰。在字典中創建自定義密鑰

這裏是我創建類

public class ImageKey 
{ 
    public int RId; 
    public int EId; 
    public int LId; 

    public ImageKey(int rId, int eId, int lId) 
    { 
     RId = rId; 
     EId = eId; 
     LId = lId; 
    } 


    public bool Equals(ImageKey x, ImageKey y) 
    { 
     return x.RId == y.RId && x.LId == y.LId && 
       x.EId == y.EId; 
    } 

    public int GetHashCode(ImageKey obj) 
    { 
     int hash = 13; 
     hash = (hash * 7) + obj.RId.GetHashCode(); 
     hash = (hash * 7) + obj.EId.GetHashCode(); 
     hash = (hash * 7) + obj.LId.GetHashCode(); 
     return hash; 
    } 

} 

我用它作爲像

HashSet<ImageKey> resourcesId = new HashSet<ImageKey>(); 

一個HashSet作爲一個字典

var enteries = new Dictionary<ImageKey, int>(); 

但的containsKey這個語句失敗當我重複並嘗試查看是否有匹配的密鑰

ImageKey key = new ImageKey(rId, eId, lId); 
bool knownId = enteries.ContainsKey(key); 
if (!knownId) 
{ 
    enteries.Add(key, new IgaEntry()); 
} 
+0

「失敗」是什麼意思? – 2014-10-16 17:48:17

+0

'x.LId == y.Ld'是一個錯字嗎?更重要的是,你的構造函數沒有意義。 – 2014-10-16 17:51:33

+2

我相信你會需要使用「覆蓋」關鍵字「等於」和「GetHashCode」這個工作。 – McGarnagle 2014-10-16 17:53:21

回答

4

您類需要重寫object.Equals,實現IEquatable<T>接口,或實現IEqualityComparer<T>並把它傳遞作爲keyComparer到詞典的構造。 此外,您還需要覆蓋GetHashCode方法以避免意外的行爲,make sure you do it right

否則,您的課程將通過參考進行比較。

Refer Marc's answer here的樣本。