简体   繁体   中英

C# Overriding the GetHashCode method

In this example, the poster has overridden the get hash code method. I understand that this has been done in order to provide a better hash value for the returned object, to reduce the number of collisions, and therefore reduce the number of occasions it will be necessary to call Equals() .

What i would like to know, is how this algorithm been calculated:

return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();

Is there a particular reason that the numbers in question were chosen? Could i have simply picked my own numbers to put into it?

Generally you should choose primes. This helps you to avoid getting the same hash-value for different input parameters.

Prime numbers are usually used in hashcode computation to minimize the collisions. If you search for hashcode and prime numbers on this iste, you will find some detailed explanations on this (note that it is note language specific):

You typically want to use prime numbers (as is done above) because it reduces the chance of collisions (two instances yielding same result). For more info, see: http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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