c# "The given key was not present in the dictionary" when key 本身就是一个类型

c# "The given key was not present in the dictionary" when key is a type itself

这是我的代码:

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 } ] );
}

但是我在调​​用时收到错误 "The given key was not present in the dictionary":

GetValList( MyValsType.File, "LINK");

你能说说为什么吗?非常感谢。

如果您能够使用 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(); 
    }

当您使用 class 作为字典的键时,class 必须正确实现 GetHashCode() 和 Equals: Dictionary 调用这两个方法来理解 "that key" 与 "that other key" 相同:如果 2 个实例 xy return GetHashCode()x.Equals(y) == true; 的值相同,则 2 个键匹配.

不在您的 MyKeyType class 中提供两个覆盖将导致 object.GetHashCode()object.Equals 在运行时被调用:这些将 return 匹配仅当 x 和 y 是对同一实例的引用时(即 object.ReferenceEquals(x, y) == true

许多 .Net 框架类型(例如字符串、数字类型、日期时间等)正确地实现了这两种方法。对于您定义的 classes,您必须在代码中实现它们