为什么很重要重写GetHash code等于方法被重写时? [英] Why is it important to override GetHashCode when Equals method is overridden?
问题描述
考虑下面的类
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
我已经覆盖了等于
方法,因为富
重新present为<$ C $一行C>富桌上。这是重写preferred方法 GetHash code
?
I have overridden the Equals
method because Foo
represent a row for the Foo
s table. Which is the preferred method for overriding the GetHashCode
?
为什么很重要重写 GetHash code
?
推荐答案
是的,这是很重要的,如果你的项目将被用作在字典中的关键,或的HashSet&LT; T&GT;
等等 - 因为这是使用(在没有自定义的的IEqualityComparer&LT的; T&GT;
)组项目入桶。如果散列code两个项目不匹配,他们可能的从不的被认为是等于(等于
根本不会被调用)。
Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>
, etc - since this is used (in the absence of a custom IEqualityComparer<T>
) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals
will simply never be called).
的 GetHash code()
方法应当反映等于
逻辑;规则是:
The GetHashCode()
method should reflect the Equals
logic; the rules are:
- 如果两件事情是相等的(
等于(...)==真
),那么他们的必须的返回相同的值GetHash code()
- 如果在
GetHash code()
是平等的,它的不的需要为他们是相同的;这是一个碰撞,和等于
将被调用,看它是否是一个真正的平等与否。
- if two things are equal (
Equals(...) == true
) then they must return the same value forGetHashCode()
- if the
GetHashCode()
is equal, it is not necessary for them to be the same; this is a collision, andEquals
will be called to see if it is a real equality or not.
在这种情况下,它看起来像返回FooId;
是一个合适的 GetHash code()
的实施。如果您正在测试多个属性,通常使用code像下面,以减少碰撞对角(即让新的Foo(3,5)
有将它们组合不同的散列code到新的Foo(5,3)
)
In this case, it looks like "return FooId;
" is a suitable GetHashCode()
implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that new Foo(3,5)
has a different hash-code to new Foo(5,3)
):
int hash = 13;
hash = (hash * 7) + field1.GetHashCode();
hash = (hash * 7) + field2.GetHashCode();
...
return hash;
哦 - 为了方便起见,你也可以考虑提供覆盖时==
和 =
运营商<$ C! $ C>等于和 GetHash code
。
当你犯了这个错误会发生什么情况的演示是<一个href=\"http://stackoverflow.com/questions/638761/c-gethash$c$c-override-of-object-containing-generic-array/639098#639098\">here.
A demonstration of what happens when you get this wrong is here.
这篇关于为什么很重要重写GetHash code等于方法被重写时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!