简体   繁体   English

C# 覆盖 GetHashCode 方法

[英]C# Overriding the GetHashCode method

In this example, the poster has overridden the get hash code method.示例中,发布者已覆盖获取 hash 代码方法。 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() .我知道这样做是为了为返回的 object 提供更好的 hash 值,以减少碰撞次数,从而减少需要调用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):如果你在这个 iste 上搜索哈希码和素数,你会找到一些详细的解释(注意它是特定于语言的):

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/有关详细信息,请参阅: http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/

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

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