[英]What are the rules I should follow to ensure GetHashCode() method returns unique value for an object?
What are the rules I should follow to ensure GetHashCode() method returns unique value for an object? 为确保GetHashCode()方法返回对象的唯一值,应遵循哪些规则?
For example: 例如:
You shouldn't even aim for GetHashCode()
returning a unique value for each object. 你甚至不应该瞄准
GetHashCode()
返回的每个对象的唯一值。 That's not the point of GetHashCode()
. 这不是点
GetHashCode()
。
Eric Lippert has a great post about hash codes which you should read thoroughly. 埃里克·利珀特(Eric Lippert)撰写了一篇很棒的有关哈希码的文章 ,您应该仔细阅读。 Basically you want to end up with something which will always return the same value for two equal objects (and you need to work out what you mean by equal) and is likely to return different values for two non-equal objects.
基本上,您希望最终得到的东西将始终为两个相等的对象返回相同的值(并且您需要计算出相等的含义),并且可能为两个非相等的对象返回不同的值。
Personally I tend to use an implementation like this: 我个人倾向于使用这样的实现:
public override int GetHashCode()
{
int hash = 17;
hash = hash * 31 + field1.GetHashCode();
hash = hash * 31 + field2.GetHashCode();
hash = hash * 31 + field3.GetHashCode();
...
return hash;
}
Things to watch out for: 注意事项:
If your fields can be null, you need to check for that while calculating your hash. 如果您的字段可以为null,则需要在计算哈希值时检查该字段。 For example:
例如:
hash = hash * 31 + (field2 == null ? 0 : field2.GetHashCode());
You don't necessarily need a fool proof hashcode because you also need to override Equals for comparison. 您不一定需要简单的哈希码,因为您还需要覆盖Equals进行比较。 Usually what I do is take the values I know are different across objects, concatenate them into a string and return the hash for that.
通常,我要做的是将我知道的值在对象之间不同,将它们连接成字符串并返回该哈希值。
I think your answer is here: See Jon Skeet answer, generally pretty reliable way to calculate it. 我认为您的答案在这里:请参阅Jon Skeet答案,这是一种相当可靠的计算方法。 Proved by time :)
时间证明:)
What is the best algorithm for an overridden System.Object.GetHashCode? 重写System.Object.GetHashCode的最佳算法是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.