压倒一切的GetHashCode() [英] Overriding GetHashCode()

查看:85
本文介绍了压倒一切的GetHashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章,乔恩斯基特提到他通常使用这种算法来覆盖的的GetHashCode ()

In this article, Jon Skeet mentioned that he usually uses this kind of algorithm for overriding GetHashCode().

public override int GetHashCode()
{
  unchecked // Overflow is fine, just wrap
  {
    int hash = 17;
    // Suitable nullity checks etc, of course :)
    hash = hash * 23 + Id.GetHashCode();
    return hash;
  }
}

现在,我已经使用这个尝试过,但ReSharper的告诉我,该方法的的GetHashCode()的应只使用只读域散列(它编译正常,虽然)。这将是一个很好的做法,因为现在我真的不能有我的字段是只读的?

Now, I've tried using this, but Resharper tells me that the method GetHashCode() should be hashing using only read-only fields (it compiles fine, though). What would be a good practice, because right now I can't really have my fields to be read-only?

我试过产生由ReSharper的这种方法,这里的结果

I tried generating this method by Resharper, here's the result.

public override int GetHashCode()
{
  return base.GetHashCode();
}

这不难有作为,说实话...

This doesn't contribute much, to be honest...

推荐答案

如果您所有的领域是可变的,你必须实施的GetHashCode 的方法,我恐怕这是你需要有落实。

If all your fields are mutable and you have to implement GetHashCode method, I am afraid this is the implementation you would need to have.

public override int GetHashCode() 
{ 
    return 1; 
} 



是的,这是低效的,但这至少是正确的。

Yes, this is inefficient but this is at least correct.

问题是,的GetHashCode 正在使用的词典与HashSet的集合,以每个项目放在一个水桶。对象被放置到HashSet的或字典之后根据某些可变字段如果哈希码计算并字段被真正改变,对象不再能够从HashSet的或字典中找到。

The problem is that GetHashCode is being used by Dictionary and HashSet collections to place each item in a bucket. If hashcode is calculated based on some mutable fields and the fields are really changed after the object is placed into the HashSet or Dictionary, the object can no longer be found from the HashSet or Dictionary.

请注意,与所有对象返回相同的HashCode 1,这基本上意味着被投入在HashSet的或字典同一个桶中的所有对象。所以,总有只有一个的HashSet或字典单斗。当试图查找的对象,它会做在各只水桶内的对象的相等性检查。这就像在做一个链表的搜索。

Note that with all the objects returning the same HashCode 1, this basically means all the objects are being put in the same bucket in the HashSet or Dictionary. So, there is always only one single bucket in the HashSet or Dictionary. When trying to lookup the object, it will do a equality check on each of the objects inside the only bucket. This is like doing a search in a linked list.

有人可能会认为,实施基于可变域的哈希码可以是很好,如果我们可以确保域之后从未改变对象添加到的HashCode或字典集合。我个人的看法是,这是容易出错。有人接手你的代码,两年后可能没有意识到这一点,不小心打破了代码。

Somebody may argue that implementing the hashcode based on mutable fields can be fine if we can make sure fields are never changed after the objects added to HashCode or Dictionary collection. My personal view is that this is error-prone. Somebody taking over your code two years later might not be aware of this and breaks the code accidentally.

这篇关于压倒一切的GetHashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆