這是我的代碼: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");
你能說出原因嗎?提前謝謝了。
您將新對象傳遞給字典,因此它不存在。 –
感謝Maxim。但有沒有其他方式沒有使用新的關鍵字? 我想查找(MyValsType.File,「LINK」)的相應值,並且我不打算使用「new」,但我不知道如何爲此目的設置適當的參數。 – dghadagh
爲什麼?因爲給定的鍵不存在於字典中。我猜你想要找到其屬性('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