有什么可以去错的,如果其中一个出现故障覆盖GetHash code()重写的Equals()时? [英] What can go wrong if one fails to override GetHashCode() when overriding Equals()?
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethash$c$c-when-equals-method-is-overridden">Why是很重要的覆盖GetHash code当equals方法被重写?
在C#中,有什么特别能如果不能覆盖GetHash code出问题()重写的Equals()时?
In C#, what specifically can go wrong if one fails to override GetHashCode() when overriding Equals()?
推荐答案
最明显的办法是映射结构。
The most visible way is for mapping structures.
这确实这将对联合国的predictable行为为重点的字典或哈希表使用时,任何类。是的原因是,实现同时使用GetHash code和等于正确地发现,在表中的值。短版的算法是以下
Any class which does this will have unpredictable behavior when used as the Key for a Dictionary or HashTable. The reason being is that the implementation uses both GetHashCode and Equals to properly find a value in the table. The short version of the algorithm is the following
- 取的散列code中的模量桶的数量,这就是斗指数
- 指定键,并在特定的水桶每个按键呼叫.Equals()。
- 如果存在匹配,它是值,不匹配=没有价值。
未能保持GetHash code和等于同步将彻底打破这种算法(以及许多其他)。
Failing to keep GetHashCode and Equals in sync will completely break this algorithm (and numerous others).
这篇关于有什么可以去错的,如果其中一个出现故障覆盖GetHash code()重写的Equals()时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!