我有一个以列表为键的字典:
private Dictionary<List<custom_obj>, string> Lookup;
我正在尝试使用 ContainsKey,但它似乎不起作用,我也不知道为什么。 这是我的 Visual Studio 即时窗口中的调试信息:
?Lookup.Keys.ElementAt(7)[0]
{custom_obj}
Direction: Down
SID: 2540
?Lookup.Keys.ElementAt(7)[1]
{custom_obj}
Direction: Down
SID: 2550
searchObject[0]
{custom_obj}
Direction: Down
SID: 2540
searchObject[1]
{custom_obj}
Direction: Down
SID: 2550
?Lookup.ContainsKey(searchObject)
false
以我的常识,最后一个 ContainsKey 应该是真的。希望我在这里包含了足够的信息……有什么想法吗?
谢谢!
最佳答案
List<custom_obj>
作为键的实例在引用上不等于 searchObject 引用的实例。
如果您希望字典使用列表中的值而不是引用相等来查找匹配键,则必须在 constructor 中提供一个 IEqualityComparer字典(因为您不能在 List<T>
中覆盖 Equals 和 GetHashCode)。
关于C# 列表作为字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10020541/