【发布时间】:2011-09-19 19:39:26
【问题描述】:
我有一个字典,每次调用 ContainsKey 方法时它都会返回 false。举个例子
Boolean found = dict.ContainsKey(new Group("group1", "test"));
尽管 Visual Studio 调试器显示名称为“group1”且类型为“test”的组存在于 dict 中,但找到的变量为 false。怎么回事?
我的 Group 类有两个 String 字段(类型和名称),我重写了 Equals 方法
public override bool Equals(object obj)
{
Group otherGroup = (Group)obj;
return this.name == otherGroup.name && this.type == otherGroup.type;
}
【问题讨论】:
-
GetHashCode 也被覆盖了?
-
你好像被not overriding GetHashCode烧死了。
-
如果你覆盖
Equals,你也应该总是覆盖GetHashCode,这样它就会为你的Group对象返回一个唯一的值。另外,重复:stackoverflow.com/questions/6129497/c-dictionary-containskey -
@CoryLarson 感谢您的问题参考;我在搜索中没有找到那个
标签: c# .net .net-4.0 dictionary