简体   繁体   English

何时重写GetHashCode()?

[英]When to override GetHashCode()?

我们什么时候应该覆盖' System '命名空间中' Object '类提供的GetHashCode ()方法?

When you override Equals , basically. 当你重写Equals ,基本上。 When you want to provide a different idea of equality than simple reference equality. 当你想提供一个不同的平等概念而不是简单的引用平等。

String is a good example of this - two strings are equal (under a simple Equals call) if they represent the same sequence of characters. String就是一个很好的例子 - 如果它们代表相同的字符序列,则两个字符串相等(在简单的Equals调用下)。 The hash code reflects this, such that if two strings are equal they will have the same hash code. 哈希码反映了这一点,这样如果两个字符串相等,它们将具有相同的哈希码。 (The reverse isn't necessarily true - two unequal strings can have the same hash code, but it's unlikely.) (反过来不一定正确 - 两个不相等的字符串可以具有相同的哈希码,但不太可能。)

(Strings are tricky in other ways, mind you - there are lots of different ideas of equality based on culture and casing, but String.Equals just looks at the UTF-16 code points which make up the string, and compares them in the simplest conceivable fashion.) (字符串在其他方面很棘手,请注意 - 基于文化和套管有很多不同的平等概念,但String.Equals只是查看构成字符串的UTF-16代码点,并在最简单的情况下对它们进行比较可以想象的时尚。)

如果你的类型应该遵循值语义(比较内容)而不是引用语义(比较对象标识),你应该编写自己的实例对象覆盖.Equals()。

如果重写Equals ,则必须覆盖GetHashCode

"The GetHashCode method can be overridden by a derived type. Value types must override this method to provide a hash function that is appropriate for that type and to provide a useful distribution in a hash table. For best results, the hash code must be based on the value of an instance field or property instead of a static field or property. “GetHashCode方法可以被派生类型覆盖。值类型必须覆盖此方法,以提供适合该类型的哈希函数,并在哈希表中提供有用的分布。为了获得最佳结果,哈希代码必须基于关于实例字段或属性的值而不是静态字段或属性。

Objects used as a key in a Hashtable object must also override the GetHashCode method because those objects must generate their own hash code. 用作Hashtable对象中的键的对象还必须覆盖GetHashCode方法,因为这些对象必须生成自己的哈希代码。 If an object used as a key does not provide a useful implementation of GetHashCode, you can specify a hash code provider when the Hashtable object is constructed. 如果用作键的对象不提供GetHashCode的有用实现,则可以在构造Hashtable对象时指定哈希代码提供程序。 Prior to the .NET Framework version 2.0, the hash code provider was based on the System.Collections..::.IHashCodeProvider interface. 在.NET Framework 2.0版之前,哈希代码提供程序基于System.Collections .. ::。IHashCodeProvider接口。 Starting with version 2.0, the hash code provider is based on the System.Collections..::.IEqualityComparer interface." 从2.0版开始,哈希码提供程序基于System.Collections .. ::。IEqualityComparer接口。“

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM