问题描述
可能重复:
<一href="http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethash$c$c">What是一个覆盖System.Object.GetHash code最好的算法?
我需要重写GetHash code方法的类型,它包括三个串。这是我的code:
I need to override GetHashCode method for a type which consists of three strings. Here is my code:
protected override int GetHashCode()
{
return str1.GetHashCode() + str2.GetHashCode() + str3.GetHashCode();
}
什么是这种方法实现一个安全的方式?
What is a safe way of this method implementation?
推荐答案
最好的办法是避免任何会产生相同的哈希值code,如果你:
The best way is to avoid anything that would produce the same hash code if you:
- 交换操作数的顺序
- 有一个大部分零值,只是将非零值围绕
另外两个(本身)和异失败对这些帐户。
Both addition (by itself) and XOR fails on these accounts.
下面是一个更好的方法:
Here's a better approach:
public override int GetHashCode()
{
unchecked
{
int result = 37; // prime
result *= 397; // also prime (see note)
if (str1 != null)
result += str1.GetHashCode();
result *= 397;
if (str2 != null)
result += str2.GetHashCode();
result *= 397;
if (str2 != null)
result += str2.GetHashCode();
return result;
}
}
无论您是使用添加或XOR里面那个code为待讨论,我看到的例子同时使用没有明确的分析,是优良的(即均匀分布)。选择一个,并用它去。
Whether you use addition or XOR inside that code is up for debate, I've seen examples using both with no clear analysis of which is superior (ie. uniform distribution). Pick one and go with it.
397是所用的ReSharper插件时,它会产生GetHash code实现的,而且显然选择,因为它通常溢出int的范围,从而混合位好一点。有围绕GetHash code实现这种特殊的格式很多理论,但它是最常用的。
397 is the default value used by the ReSharper addin when it generates GetHashCode implementations, and is apparently selected because it typically overflows the range of the int and thus mixes bits a bit better. There are many theories around this particular format of GetHashCode implementation, but it's the most used one.
这篇关于定制型GetHash code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!