C#: override GetHashCode, what does this code do?

本秂侑毒 提交于 2019-12-11 03:21:59

问题


Here's the code I found in the Nhibernate 3 Beginners Guide to override GetHashCode. I don't understand why it uses result * 397. If 397 just a random number he use to generate unique result??

Can we just GetHashCode for firstname, middlename and lastname, then combine it together using ^, it should also generate an unique result.

public override int GetHashCode()
{
   unchecked
   {
       var result = FirstName.GetHashCode();
       result = (result*397) ^ (MiddleName != null ? MiddleName.GetHashCode() : 0);
       result = (result*397) ^ LastName.GetHashCode();
       return result;
   }
}

回答1:


Multiplying the intermediate hash code by a given number as part of each combination will mean the ordering of the combined has codes will not be irrelevant.

If you just did an exclusive or on the three name parts, then "John William James" would give the same hash code as "James William John".

397 is chosen because it is a prime number large enough sufficient to cause the hash code to overflow, and this helps generate a good distribution of hash codes.

The overflow is the reason this code has to sit inside an unchecked block.




回答2:


Multiplication is also basically bit shift (exactly bit shift if * a power of 2), so it has that effect on the computed value here, but as to why precisely 397, well that is just how this paticular hash algorithm was written. Yes, other values, indeed more complex algorithms are often used as a hashing algorithm.

This is different from simply XORing 3 hashcodes together, and will result in far fewer 'hash collisions' - where 2 (or more) objects hash to the same value (something to be minimized if not avoided in a good hash function)



来源:https://stackoverflow.com/questions/7620405/c-override-gethashcode-what-does-this-code-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!