且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较对象时等于VS GetHash code

更新时间:2022-03-29 23:53:57

下面是你需要了解的等于 GetHash $的关系C $ç

Here's what you need to understand about the relationship between Equals and GetHashCode.

哈希codeS所使用的哈希表可以迅速找到桶,其中一个单元被预期存在。 如果元素是在两个不同的桶,假设是它们不能是相等的。

Hash codes are used by hashtables to quickly find a "bucket" in which an element is expected to exist. If elements are in two different buckets, the assumption is they cannot be equal.

这样做的结果是,你应该查看散列code,为了确定唯一性,作为一个快速的的检查:即,如果两个物体有不同的hash codeS ,他们的没有的相同(不管它们的等于方法返回)。

The outcome of this is that you should view a hash code, for purposes of determining uniqueness, as a quick negative check: i.e., if two objects have different hash codes, they are not the same (regardless of what their Equals methods return).

如果两个物体具有的一样的散列code,它们将驻留在一个哈希表的同一个桶。 然后的其等于方法将被调用,以确定相等。

If two objects have the same hash code, they will reside in the same bucket of a hash table. Then their Equals methods will be called to determine equality.

所以 GetHash code 必须的返回相同的值要被认为是相等的两个对象。

So GetHashCode must return the same value for two objects that you want to be considered equal.