我需要覆盖由三个字符串组成的类型的GetHashCode方法.这是我的代码:
protected override int GetHashCode()
{
return str1.GetHashCode() + str2.GetHashCode() + str3.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
这种方法实现的安全方法是什么?
ang*_*son 19
最好的方法是避免在下列情况下产生相同哈希码的任何内容:
这些帐户的添加(单独)和XOR都失败了.
这是一个更好的方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
无论你在代码中使用加法还是异或都是有争议的,我已经看到使用两者的例子,没有明确分析哪个是优越的(即均匀分布).选择一个并继续使用它.
397是ReSharper插件在生成GetHashCode实现时使用的默认值,并且显然是因为它通常溢出int的范围而因此混合位更好一些.围绕这种特定格式的GetHashCode实现有很多理论,但它是最常用的.
| 归档时间: |
|
| 查看次数: |
7733 次 |
| 最近记录: |