问题描述
我有一个由列表键入的字典: 私人字典< List< custom_obj>,string>抬头;
我试图使用ContainsKey,但似乎没有工作,我有不知道为什么
这是Visual Studio立即窗口中的调试信息:
?Lookup.Keys.ElementAt(7)[ 0]
{custom_obj}
方向:向下
SID:2540
?Lookup.Keys.ElementAt(7)[1]
{custom_obj}
方向:向下
SID:2550
searchObject [0]
{custom_obj}
方向:向下
SID:2540
searchObject [1]
{custom_obj}
方向:向下
SID:2550
?Lookup.ContainsKey(searchObject)
false
在我的常识上,最后一个ContainsKey应该是true。希望我在这里提供足够的信息...任何想法?
谢谢!
作为关键字的列表< custom_obj>
实例与searchObject引用的实例是不相等的。
如果您希望字典使用列表中的值而不是引用等式来查找匹配的键,则必须在(因为您不能覆盖 List< T>
中的Equals和GetHashCode)
I have a dictionary which is keyed by a List:
private Dictionary<List<custom_obj>, string> Lookup;
I'm trying to use ContainsKey, but it doesn't seem to be working, and I have no idea why.Here is the debug information from my Visual Studio Immediate Window:
?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
In my common sense, that last ContainsKey should be true. Hopefully I've included enough information here... any ideas?
Thanks!
The List<custom_obj>
instance acting as a key is referentially unequal to the instance referred to by searchObject.
If you want the dictionary to use the values in the list instead of referential equality to find matching keys, you must supply an IEqualityComparer in the constructor of the dictionary (since you can't override Equals and GetHashCode in List<T>
).
这篇关于C#列为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!