2015-12-05 44 views
-1

這是我的代碼:C#「給定的鍵不存在在詞典中」時,關鍵是一種自身

public class MyKeyType 
{ 
    public int x; 
    public string operationStr; 
} 

private static Dictionary<MyKeyType, List<int>> m_Dict = new Dictionary<MyKeyType, List<int>> 
{ 
    { new MyKeyType { x = MyValsType.File, operationStr = "LINK" }, new List<int> { 1,2,3,4,5 } }, 
    { new MyKeyType { x = MyValsType.File, operationStr = "COPY" }, new List<int> { 10,20,30,40,50 } }, 
    ..... 
} 

List<int> GetValList(int i, string op) 
{ 
    // The following line causes error: 
    return (m_Dict [ new MyKeyType { x = i, operationStr = op } ]); 
} 

但我得到的錯誤「給定的鍵不存在在詞典中」時我致電:

GetValList(MyValsType.File, "LINK"); 

你能說出原因嗎?提前謝謝了。

+1

您將新對象傳遞給字典,因此它不存在。 –

+0

感謝Maxim。但有沒有其他方式沒有使用新的關鍵字? 我想查找(MyValsType.File,「LINK」)的相應值,並且我不打算使用「new」,但我不知道如何爲此目的設置適當的參數。 – dghadagh

+1

爲什麼?因爲給定的鍵不存在於字典中。我猜你想要找到其屬性('x'和'operationStr')與前一個條目的屬性匹配的鍵,但這並不意味着該條目是相同的。例如:'MyKeyType test = new MyKeyType {x = 1,operationStr =「1」}; m_Dict.Add(test,new List (){1,2,3});'如果你現在做'MyKeyType test0 = new MyKeyType {x = 1,operationStr =「1」}; 列表 test2 = m_Dict [test0];'你會得到一個錯誤。順便說一句,下次你應該儘量做一個小小的努力,比如用這個簡單的例子來清楚地問一下。 – varocarbas

回答

4

,班裏有正確實現GetHashCode()和equals:字典調用這兩種方法來理解「那個鍵」與「其他鍵」相同:如果2個實例xy返回的值與GetHashCode()x.Equals(y) == true;的值相同,則2個鍵匹配。

不提供兩個覆蓋在你的MyKeyType類將導致object.GetHashCode()object.Equals被稱爲在運行時:這些都將返回匹配僅當x和y是相同的實例(即object.ReferenceEquals(x, y) == true

許多參考.Net框架類型(例如字符串,數字類型,dateTime等)正確地實現了這兩種方法。對於您定義的類,您必須在代碼中實現它們

+0

太好了。謝謝Gian。 – dghadagh

1

如果你能使用LINQ,你可以改變你的GetValList()來:當您使用類作爲字典的關鍵

static List<int> GetValList(int i, string op) 
    { 
     return m_Dict.Where(x => x.Key.x == i && x.Key.operationStr.Equals(op)).Select(x => x.Value).FirstOrDefault(); 
    } 
+0

是的,LINQ方法是最簡單的方法。 – Fka

+0

太棒了! 。謝謝。 – dghadagh

相關問題