简体   繁体   English

C#Equals和GetHashCode

[英]C# Equals and GetHashCode

There's a job interview question I encountered some days ago: How can 2 C# objects or primitive types have the same result for their un-overridden GetHashCode() method but Equals() false? 几天前我遇到了一个求职面试问题:2个C#对象或原始类型对于未被重写的GetHashCode()方法有什么相同的结果,但是Equals() false? I was directed to the primitive type long and couldn't think of a solution for that. 我被引导到原始类型long ,并没有想到解决方案。

The rule is that if Equals returns true, then GetHashCode must return the same value, but not the other way around. 规则是如果Equals返回true,则GetHashCode必须返回相同的值,但不是相反。

Consider this: GetHashCode returns an int. 考虑一下:GetHashCode返回一个int。 The Type long has more possible values than the Type int. Type long具有比Type int更多的可能值。 This means that more than one long value will produce the same hash code as another long value. 这意味着多个long值将产生与另一个long值相同的哈希码。 This is called the Pigeon-Hole Principle: http://en.wikipedia.org/wiki/Pigeonhole_principle 这被称为鸽子洞原则: http//en.wikipedia.org/wiki/Pigeonhole_principle

A hashcode is a 32-bit integer - how are you going to get a unique hash for every 64-bit long? 哈希码是一个32位整数 - 你如何获得每64位长的唯一哈希值?

A hash-code is supposed to be as-unique-as-possible in order to be as efficient as possible. 为了尽可能高效,哈希码应该尽可能唯一。 Equality is a mathematical rule which can't be broken. 平等是一个不能被打破的数学规则。

This is mathematics. 这是数学。 The pigeonhole principle states that if you have 101 pigeons to put in 100 holes, than you will have to put 2 pigeons in the same hole. 鸽巢原理指出,如果你有101只鸽子放入100个孔,比你不得不把2只鸽子同穴。

As follows, if you have 2^64 possible longs, and 2^32 possible hashcodes (signed int), then you're bound to get the same hash code for different longs. 如下所示,如果您有2 ^ 64个可能的长度和2 ^ 32个可能的哈希码(signed int),那么您必须获得不同长度的相同哈希码。

Well, since long is 8-byted and int is only 4, you can say there will be A LOT of hash code collisions. 那么,既然long为8 byted和int只有4,你可以说会有哈希码碰撞了很多

For example, 5 and 4294967300 have the same hash code. 例如, 54294967300具有相同的哈希码。 Which is 5. 这是5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM