C# 中的 GetHashCode 指南

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/462451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:21:46  来源:igfitidea点击:

GetHashCode Guidelines in C#

c#.nethashcode

提问by Joan Venge

I read in the Essential C# 3.0 and .NET 3.5 book that:

我在 Essential C# 3.0 和 .NET 3.5 书中读到:

GetHashCode()'s returns over the life of a particular object should be constant (the same value), even if the object's data changes. In many cases, you should cache the method return to enforce this.

GetHashCode() 在特定对象的生命周期内的返回值应该是恒定的(相同的值),即使对象的数据发生变化。在许多情况下,您应该缓存方法返回以强制执行此操作。

Is this a valid guideline?

这是一个有效的指南吗?

I have tried a couple built-in types in .NET and they didn't behave like this.

我在 .NET 中尝试了几种内置类型,但它们的行为并不像这样。

采纳答案by Jeff Yates

The answer is mostly, it is a valid guideline, but perhaps not a valid rule. It also doesn't tell the whole story.

答案主要是,它是一个有效的指南,但可能不是一个有效的规则。它也没有讲述整个故事。

The point being made is that for mutable types, you cannot base the hash code on the mutable data because two equal objects must return the same hash code and the hash code has to be valid for the lifetime of the object. If the hash code changes, you end up with an object that gets lost in a hashed collection because it no longer lives in the correct hash bin.

重点是对于可变类型,您不能将哈希码基于可变数据,因为两个相等的对象必须返回相同的哈希码,并且哈希码必须在对象的生命周期内有效。如果散列码改变,你最终会得到一个对象,它会在散列集合中丢失,因为它不再存在于正确的散列箱中。

For example, object A returns hash of 1. So, it goes in bin 1 of the hash table. Then you change object A such that it returns a hash of 2. When a hash table goes looking for it, it looks in bin 2 and can't find it - the object is orphaned in bin 1. This is why the hash code must not change for the lifetime of the object, and just one reason why writing GetHashCode implementations is a pain in the butt.

例如,对象 A 返回 1 的哈希值。因此,它进入哈希表的 bin 1。然后更改对象 A 使其返回 2 的散列值。当散列表查找它时,它会在 bin 2 中查找但找不到 - 该对象在 bin 1 中是孤立的。这就是散列码必须的原因在对象的生命周期内不会改变,这只是编写 GetHashCode 实现的一个原因。

Update
Eric Lippert has posted a blogthat gives excellent information on GetHashCode.

更新
Eric Lippert 发布了一个博客,其中提供了有关GetHashCode.

Additional Update
I've made a couple of changes above:

附加更新
我在上面做了一些更改:

  1. I made a distinction between guideline and rule.
  2. I struck through "for the lifetime of the object".
  1. 我区分了指南和规则。
  2. 我击穿了“在对象的生命周期内”。

A guideline is just a guide, not a rule. In reality, GetHashCodeonly has to follow these guidelines when things expect the object to follow the guidelines, such as when it is being stored in a hash table. If you never intend to use your objects in hash tables (or anything else that relies on the rules of GetHashCode), your implementation doesn't need to follow the guidelines.

指南只是指南,而不是规则。实际上,GetHashCode只有在期望对象遵循这些准则时才需要遵循这些准则,例如当它被存储在哈希表中时。如果您从不打算在哈希表(或任何其他依赖于 规则的对象)中使用您的对象GetHashCode,则您的实现不需要遵循这些准则。

When you see "for the lifetime of the object", you should read "for the time the object needs to co-operate with hash tables" or similar. Like most things, GetHashCodeis about knowing when to break the rules.

当您看到“对象的生命周期”时,您应该阅读“对象需要与哈希表合作的时间”或类似内容。像大多数事情一样,GetHashCode是关于知道何时打破规则。

回答by Jon B

From MSDN

来自MSDN

If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.

The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.

For the best performance, a hash function must generate a random distribution for all input.

如果两个对象比较相等,则每个对象的 GetHashCode 方法必须返回相同的值。但是,如果两个对象不相等,则两个对象的 GetHashCode 方法不必返回不同的值。

只要不修改决定对象 Equals 方法返回值的对象状态,对象的 GetHashCode 方法就必须始终返回相同的哈希码。请注意,这仅适用于应用程序的当前执行,如果再次运行该应用程序,可能会返回不同的哈希码。

为了获得最佳性能,散列函数必须为所有输入生成随机分布。

This means that if the value(s) of the object change, the hash code should change. For example, a "Person" class with the "Name" property set to "Tom" should have one hash code, and a different code if you change the name to "Jerry". Otherwise, Tom == Jerry, which is probably not what you would have intended.

这意味着如果对象的值发生变化,哈希码也应该发生变化。例如,“Name”属性设置为“Tom”的“Person”类应该有一个哈希码,如果您将名称更改为“Jerry”,则应该有一个不同的代码。否则,Tom == Jerry,这可能不是您想要的。



Edit:

编辑

Also from MSDN:

同样来自 MSDN:

Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly.

覆盖 GetHashCode 的派生类也必须覆盖 Equals 以保证被视为相等的两个对象具有相同的哈希码;否则,Hashtable 类型可能无法正常工作。

From MSDN's hashtable entry:

来自MSDN 的哈希表条目

Key objects must be immutable as long as they are used as keys in the Hashtable.

键对象必须是不可变的,只要它们用作 Hashtable 中的键即可。

The way I read this is that mutable objects shouldreturn different hashcodes as their values change, unlessthey are designed for use in a hashtable.

我读这个的方式是,可变对象应该在它们的值改变时返回不同的哈希码,除非它们被设计为在哈希表中使用。

In the example of System.Drawing.Point, the object is mutable, and doesreturn a different hashcode when the X or Y value changes. This would make it a poor candidate to be used as-is in a hashtable.

在 System.Drawing.Point 的示例中,对象是可变的,并且在 X 或 Y 值更改时确实返回不同的哈希码。这将使其成为在哈希表中按原样使用的糟糕候选者。

回答by petr k.

Not directly answering your question, but - if you use Resharper, do not forget it has a feature that generates a reasonable GetHashCode implementation (as well as the Equals method) for you. You can of course specify which members of the class will be taken into account when computing the hashcode.

不是直接回答您的问题,但是 - 如果您使用 Resharper,请不要忘记它具有为您生成合理的 GetHashCode 实现(以及 Equals 方法)的功能。您当然可以指定在计算哈希码时将考虑类的哪些成员。

回答by Justin R.

This is good advice. Here's what Brian Pepin has to say on the matter:

这是一个很好的建议。以下是 Brian Pepin 对此事的看法:

This has tripped me up more than once: Make sure GetHashCode always returns the same value across the lifetime of an instance. Remember that hash codes are used to identify "buckets" in most hashtable implementations. If an object's "bucket" changes, a hashtable may not be able to find your object. These can be very hard bugs to find, so get it right the first time.

这不止一次让我感到困惑:确保 GetHashCode 在实例的整个生命周期中始终返回相同的值。请记住,在大多数哈希表实现中,哈希码用于标识“桶”。如果对象的“存储桶”发生变化,哈希表可能无法找到您的对象。这些可能是很难找到的错误,所以第一次就做对。

回答by DavidN

The hashcode never changes, but it's also important to understand where the Hashcode is coming from.

哈希码永远不会改变,但了解哈希码的来源也很重要。

If your object is using value semantics, i.e. the object's identity is defined by its values (like String, Color, all structs). If your object's identity is independent of all of its values, then the Hashcode is identified by a subset of its values. For example, your StackOverflow entry is stored in a database somewhere. If you change your name or email, your customer entry stays the same, although some values have changed (ultimately you're usually identified by some long customer id #).

如果您的对象使用值语义,即对象的身份由其值定义(如字符串、颜色、所有结构)。如果您的对象的身份与其所有值无关,则哈希码由其值的子集标识。例如,您的 StackOverflow 条目存储在某个数据库中。如果您更改您的姓名或电子邮件,您的客户条目将保持不变,尽管某些值已更改(最终您通常会通过一些很长的客户 ID # 来标识)。

So in short:

简而言之:

Value type semantics - Hashcode is defined by values Reference type semantics - Hashcode is defined by some id

值类型语义 - Hashcode 由值定义 引用类型语义 - Hashcode 由某个 id 定义

I suggest you read Domain Driven Design by Eric Evans, where he goes into entities vs value types (which is more or less what I attempted to do above) if this still doesn't make sense.

我建议你阅读 Eric Evans 的领域驱动设计,如果这仍然没有意义的话,他在那里讨论了实体与值类型(这或多或少是我在上面尝试做的)。

回答by Frederik Gheysels

I think that the documentation regarding GetHashcode is a bit confusing.

我认为有关 GetHashcode 的文档有点混乱。

On one hand, MSDN states that the hashcode of an object should never change , and be constant On the other hand, MSDN also states that the return value of GetHashcode should be equal for 2 objects, if those 2 objects are considered to be equal.

一方面,MSDN 声明对象的哈希码永远不应该改变,并且是常量另一方面,MSDN 还声明 GetHashcode 的返回值对于 2 个对象应该相等,如果这两个对象被认为是相等的。

MSDN:

微软:

A hash function must have the following properties:

  • If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
  • The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
  • For the best performance, a hash function must generate a random distribution for all input.

散列函数必须具有以下属性:

  • 如果两个对象比较相等,则每个对象的 GetHashCode 方法必须返回相同的值。但是,如果两个对象不相等,则两个对象的 GetHashCode 方法不必返回不同的值。
  • 只要不修改决定对象 Equals 方法返回值的对象状态,对象的 GetHashCode 方法就必须始终返回相同的哈希码。请注意,这仅适用于应用程序的当前执行,如果再次运行该应用程序,可能会返回不同的哈希码。
  • 为了获得最佳性能,散列函数必须为所有输入生成随机分布。

Then, this means that all your objects should be immutable, or the GetHashcode method should be based on properties of your object that are immutable. Suppose for instance that you have this class (naive implementation):

然后,这意味着您的所有对象都应该是不可变的,或者 GetHashcode 方法应该基于您的对象的不可变属性。例如,假设您有这个类(幼稚的实现):

public class SomeThing
{
      public string Name {get; set;}

      public override GetHashCode()
      {
          return Name.GetHashcode();
      }

      public override Equals(object other)
      {
           SomeThing = other as Something;
           if( other == null ) return false;
           return this.Name == other.Name;
      }
}

This implementation already violates the rules that can be found in MSDN. Suppose you have 2 instances of this class; the Name property of instance1 is set to 'Pol', and the Name property of instance2 is set to 'Piet'. Both instances return a different hashcode, and they're also not equal. Now, suppose that I change the Name of instance2 to 'Pol', then, according to my Equals method, both instances should be equal, and according to one of the rules of MSDN, they should return the same hashcode.
However, this cannot be done, since the hashcode of instance2 will change, and MSDN states that this is not allowed.

这个实现已经违反了 MSDN 中可以找到的规则。假设你有这个类的 2 个实例;instance1 的Name 属性设置为'Pol',instance2 的Name 属性设置为'Piet'。两个实例都返回不同的哈希码,而且它们也不相等。现在,假设我将 instance2 的名称更改为“Pol”,然后,根据我的 Equals 方法,两个实例应该相等,并且根据 MSDN 的规则之一,它们应该返回相同的哈希码。
但是,这是无法做到的,因为 instance2 的哈希码会发生变化,并且 MSDN 声明这是不允许的。

Then, if you have an entity, you could maybe implement the hashcode so that it uses the 'primary identifier' of that entity, which is maybe ideally a surrogate key, or an immutable property. If you have a value object, you can implement the Hashcode so that it uses the 'properties' of that value object. Those properties make up the 'definition' of the value object. This is of course the nature of a value object; you're not interested in it's identity, but rather in it's value.
And, therefore, value objects should be immutable. (Just like they are in the .NET framework, string, Date, etc... are all immutable objects).

然后,如果您有一个实体,您可以实现哈希码,以便它使用该实体的“主要标识符”,理想情况下这可能是代理键或不可变属性。如果您有一个值对象,您可以实现 Hashcode 以便它使用该值对象的“属性”。这些属性构成了值对象的“定义”。这当然是值对象的性质;你对它的身份不感兴趣,而对它的价值感兴趣。
因此,值对象应该是不可变的。(就像它们在 .NET 框架中一样,字符串、日期等……都是不可变对象)。

Another thing that comes in mind:
During which 'session' (I don't know really how I should call this) should 'GetHashCode' return a constant value. Suppose you open up your application, load an instance of an object out of the DB (an entity), and get its hashcode. It will return a certain number. Close the application, and load the same entity. Is it required that the hashcode this time has the same value as when you loaded the entity the first time ? IMHO, not.

想到的另一件事是:
在“会话”期间(我真的不知道我应该如何称呼它),“GetHashCode”应该返回一个常量值。假设您打开您的应用程序,从数据库(一个实体)中加载一个对象的实例,并获取其哈希码。它会返回一个特定的数字。关闭应用程序,并加载相同的实体。这次是否要求哈希码与您第一次加载实体时具有相同的值?恕我直言,不是。

回答by Shaun

Check out this blog post from Marc Brooks:

查看 Marc Brooks 的这篇博文:

VTOs, RTOs and GetHashCode() -- oh, my!

VTO、RTO 和 GetHashCode()——哦,天哪!

And then check out the follow up post (can't link as I'm new, but there's a link in the initlal article) which discusses further and covers some minor weaknesses in the initial implementation.

然后查看后续帖子(无法链接,因为我是新手,但初始文章中有一个链接),其中进一步讨论并涵盖了初始实现中的一些小弱点。

This was everything I needed to know about creating a GetHashCode() implementation, he even provides a download of his method along with some other utilities, in short gold.

这是我在创建 GetHashCode() 实现时需要知道的一切,他甚至提供了他的方法以及其他一些实用程序的下载,简而言之。

回答by Alex

It's been a long time, but nevertheless I think it is still necessary to give a correct answer to this question, including explanations about the whys and hows. The best answer so far is the one citing the MSDN exhaustivly - don't try to make your own rules, the MS guys knew what they were doing.

已经很长时间了,但我认为仍然有必要对这个问题给出正确的答案,包括解释为什么和如何。到目前为止,最好的答案是详尽地引用 MSDN 的答案-不要试图制定自己的规则,MS 人员知道他们在做什么。

But first things first: The Guideline as cited in the question is wrong.

但首先要注意的是:问题中引用的指南是错误的。

Now the whys - there are two of them

现在是为什么 - 其中有两个

First why: If the hashcode is computed in a way, that it does not change during the lifetime of an object, even if the object itself changes, than it would break the equals-contract.

首先为什么:如果以某种方式计算哈希码,则它在对象的生命周期内不会更改,即使对象本身发生更改,也会破坏等号合同。

Remember: "If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values."

请记住:“如果两个对象比较相等,则每个对象的 GetHashCode 方法必须返回相同的值。但是,如果两个对象不相等,则两个对象的 GetHashCode 方法不必返回不同的值。”

The second sentence often is misinterpreted as "The only rule is, that at object creation time, the hashcode of equal objects must be equal". Don't really know why, but that's about the essence of most answers here as well.

第二句话经常被误解为“唯一的规则是,在对象创建时,相等对象的哈希码必须相等”。不知道为什么,但这也是这里大多数答案的本质。

Think of two objects containing a name, where the name is used in the equals method: Same name -> same thing. Create Instance A: Name = Joe Create Instance B: Name = Peter

考虑两个包含名称的对象,其中名称在 equals 方法中使用:相同名称 -> 相同内容。创建实例 A:名称 = Joe 创建实例 B:名称 = Peter

Hashcode A and Hashcode B will most likely not be the same. What would now happen, when the Name of instance B is changed to Joe?

哈希码 A 和哈希码 B 很可能不同。现在,当实例 B 的名称更改为 Joe 时会发生什么?

According to the guideline from the question, the hashcode of B would not change. The result of this would be: A.Equals(B) ==> true But at the same time: A.GetHashCode() == B.GetHashCode() ==> false.

根据问题的指导方针,B 的哈希码不会改变。这样做的结果是:A.Equals(B) ==> true 但同时:A.GetHashCode() == B.GetHashCode() ==> false。

But exactly this behaviour is forbidden explicitly by the equals&hashcode-contract.

但正是 equals&hashcode-contract 明确禁止这种行为。

Second why: While it is - of course - true, that changes in the hashcode could break hashed lists and other objects using the hashcode, the reverse is true as well. Not changing the hashcode will in the worst case get hashed lists, where all of a lot of different objects will have the same hashcode and therefor be in the same hash bin - happens when objects are initialized with a standard value, for example.

第二个原因:虽然 - 当然 - 是真的,但哈希码的更改可能会破坏哈希列表和其他使用哈希码的对象,反之亦然。在最坏的情况下,不更改哈希码将获得哈希列表,其中所有许多不同的对象都将具有相同的哈希码,因此位于同一个哈希箱中 - 例如,当对象使用标准值初始化时会发生这种情况。



Now coming to the hows Well, on first glance, there seems to be a contradiction - either way, code will break. But neither problem does come from changed or unchanged hashcode.

现在来看看如何 好吧,乍一看,似乎有一个矛盾 - 无论哪种方式,代码都会中断。但是这两个问题都不是来自更改或未更改的哈希码。

The source of the problems is well described in the MSDN:

问题的根源在 MSDN 中有很好的描述:

From MSDN's hashtable entry:

来自 MSDN 的哈希表条目:

Key objects must be immutable as long as they are used as keys in the Hashtable.

键对象必须是不可变的,只要它们用作 Hashtable 中的键即可。

This does mean:

这确实意味着:

Any object that creates a hashvalue should change the hashvalue, when the object changes, but it must not - absolutely must not - allow any changes to itself, when it is used inside a Hashtable (or any other Hash-using object, of course).

任何创建哈希值的对象都应该在对象更改时更改哈希值,但是当它在 Hashtable(或任何其他使用 Hash 的对象,当然)中使用时,它不能 - 绝对不能 - 允许对自身进行任何更改.

First how Easiest way would of course be to design immutable objects only for the use in hashtables, that will be created as copys of the normal, the mutable objects when needed. Inside the immutable objects, it's obviusly ok to cache the hashcode, since it's immutable.

首先,最简单的方法当然是设计仅用于哈希表的不可变对象,这些对象将在需要时创建为普通可变对象的副本。在不可变对象中,缓存哈希码显然是可以的,因为它是不可变的。

Second how Or give the object a "you are hashed now"-flag, make sure all object data is private, check the flag in all functions that can change objects data and throw an exception data if change is not allowed (i.e. flag is set). Now, when you put the object in any hashed area, make sure to set the flag, and - as well - unset the flag, when it is no longer needed. For ease of use, I'd advise to set the flag automatically inside the "GetHashCode" method - this way it can't be forgotten. And the explicit call of a "ResetHashFlag" method will make sure, that the programmer will have to think, wether it is or is not allowed to change the objects data by now.

第二种方式 或者给对象一个“你现在被散列”-标志,确保所有对象数据都是私有的,检查所有可以更改对象数据的函数中的标志,如果不允许更改则抛出异常数据(即设置了标志) )。现在,当您将对象放在任何散列区域中时,请确保设置标志,并且 - 以及 - 在不再需要时取消设置标志。为了便于使用,我建议在“GetHashCode”方法中自动设置标志 - 这样就不会忘记了。并且“ResetHashFlag”方法的显式调用将确保程序员必须考虑现在是否允许更改对象数据。

Ok, what should be said as well: There are cases, where it is possible to have objects with mutable data, where the hashcode is nevertheless unchanged, when the objects data is changed, without violating the equals&hashcode-contract.

好的,应该说的是:在某些情况下,对象可能具有可变数据,但哈希码仍然不变,当对象数据更改时,不会违反 equals&hashcode-contract。

This does however require, that the equals-method is not based on the mutable data as well. So, if I write an object, and create a GetHashCode method that does calculate a value only once and stores it inside the object to return it on later calls, then I must, again: absolutely must, create a Equals method, that will use stored values for the comparison, so that A.Equals(B) will never change from false to true as well. Otherwise, the contract would be broken. The result of this will usually be that the Equals method doesn't make any sense - it's not the original reference equals, but it is neither a value equals as well. Sometimes, this may be intended behaviour (i.e. customer records), but usually it is not.

然而,这确实要求 equals 方法也不基于可变数据。因此,如果我编写一个对象,并创建一个 GetHashCode 方法,该方法只计算一次值并将其存储在对象中以在以后的调用中返回它,那么我必须再次:绝对必须创建一个 Equals 方法,该方法将使用用于比较的存储值,因此 A.Equals(B) 也永远不会从 false 变为 true。否则,合同将被破坏。这样做的结果通常是 Equals 方法没有任何意义 - 它不是原始引用等于,但它也不是值等于。有时,这可能是预期行为(即客户记录),但通常不是。

So, just make GetHashCode result change, when the object data changes, and if the use of the object inside of hash using lists or objects is intended (or just possible) then make the object either immutable or create a readonly flag to use for the lifetime of a hashed list containing the object.

因此,只要在对象数据更改时更改 GetHashCode 结果,并且如果打算(或仅可能)使用列表或对象在哈希内部使用对象,则使对象不可变或创建只读标志以用于包含对象的哈希列表的生命周期。

(By the way: All of this is not C# oder .NET specific - it is in the nature of all hashtable implementations, or more generally of any indexed list, that identifying data of objects should never change, while the object is in the list. Unexpected and unpredictable behaviour will occur, if this rule is broken. Somewhere, there may be list implementations, that do monitor all elements inside the list and do automatic reindexing the list - but the performance of those will surely be gruesome at best.)

(顺便说一句:所有这些都不是 C# oder .NET 特定的 - 它是所有哈希表实现的本质,或者更一般的任何索引列表,对象的标识数据不应该改变,而对象在列表中. 如果违反此规则,将发生意外和不可预测的行为。在某处,可能会有列表实现,它们会监视列表中的所有元素并自动重新索引列表 - 但这些的性能充其量肯定会令人毛骨悚然。)

回答by Ian Ringrose

Check out Guidelines and rules for GetHashCodeby Eric Lippert

查看Eric Lippert 的GetHashCode 指南和规则