我是否需要重写GetHash code()的引用类型?重写、类型、GetHash、code

2023-09-04 00:28:33 作者:帅气哥巛帅王

我读书最多的问题上计算器的问候 GetHash code 。但我仍然不知道我是否要重写 GetHash code 的引用类型。我拿起从某人在回答另一个问题如下:

I read most questions on StackOverflow with regards to GetHashCode. But I am still not sure whether I have to override GetHashCode on reference types. I picked up the following from someones answer in another question:

Object.GetHash code()使用一个内部   在System.Object类现场   生成的散列值。每个对象   创建被分配一个唯一的对象   密钥,存储为整数,当它是   创建。这些键从1开始,   递增每当一个新的对象   任何类型的被创建。

Object.GetHashCode() uses an internal field in the System.Object class to generate the hash value. Each object created is assigned a unique object key, stored as an integer,when it is created. These keys start at 1 and increment every time a new object of any type gets created.

如果这仍然是在.NET Framework 3.5的(有人可以证实?)真的,那么我用引用类型的默认实现中可以看到的唯一的问题就是散列code将有分布不均。

If this is still true in .NET Framework 3.5 (can someone please confirm?), then the only problem I see with the default implementations of reference types is that the hash code will have a poor distribution.

我会打破我的问题:

一)因此它建议重写 GetHash code 来,如果它用在词典抑或是默认的实现执行就好了?

a) So it it recommended to override GetHashCode to if it is used in a Dictionary or does the default implementation perform just fine?

二)我有引用类型的地方会很容易做到,因为他们有一个独特的,但什么样识别它们对那些引用类型,所有成员也引用类型的字段。我应该怎么办呢?

b) I have reference types where it would be easy to do since they have fields that identify them uniquely but what about those reference types where all members are also reference types. What should I do there?

推荐答案

您只需要重写GetHash code()的引用类型,如果你覆盖的Object.Equals()。

You only need to override GetHashCode() on reference types if you override Object.Equals().

这样做的原因是简单 - 通常,2引用将始终是不同的(a.Equals(二)==假,除非它们是相同的对象)。的GetHash code,其默认的实现()将提供2个不同的哈希值在这种情况下,所以一切都很好。

The reason for this is simple - normally, 2 references will always be distinct (a.Equals(b)==false, unless they're the same object). The default implementation of GetHashCode() will provide 2 distinct hashes in this case, so all is good.

如果你重载Equals(),但是,这种行为是不能保证。如果两个对象是相等的(根据equals()是),你需要保证他们将有相同的哈希code与GetHash code,所以你应该覆盖它。

If you override Equals(), though, this behavior is not guaranteed. If two objects are equal (as per Equals()), you need to guarantee that they'll have the same hash code with GetHashCode, so you should override it.