本文来聊聊在重写某个类的 GetHashCode 方法时,可以如何实现 GetHashCode 的返回值
按照 GetHashCode 方法的原则,要求两个对象如果 Equals 返回 true 那么一定要求 GetHashCode 也返回相同的值。当然,反过来不成立,也就是两个对象返回的 GetHashCode 的值相同,对象可以是不相等的
实现 GetHashCode 方法的方式有很多,最简单的就是通过调用基类的 GetHashCode 方法,代码如下
public override int GetHashCode()
{
return base.GetHashCode();
}
第二个方法就是通过 RuntimeHelpers 静态类的 GetHashCode 方法,代码如下
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
如果调用的 base.GetHashCode
的 base 是 object 类型的,也就是调用了 object 的 GetHashCode 方法,其实和调用 RuntimeHelpers 的 GetHashCode 方法是相同的,因为在 object 方法里面的 GetHashCode 定义如下
// GetHashCode is intended to serve as a hash function for this object.
// Based on the contents of the object, the hash function will return a suitable
// value with a relatively random distribution over the various inputs.
//
// The default implementation returns the sync block index for this instance.
// Calling it on the same objec