在 .NET 中,您需要 Equals(object) 和 GetHashCode() 兼容。但有时你不能:
public class GreaterThan32Bits
{
public int X { get; set; }
public int Y { get; set; }
}
因为数据密度大于 32 位,并且 GetHashCode 返回一个 Int32,所以您将有 3 个解决方案(假设正确实现了 GetHashCode):
避免代码重复因为不正确而被丢弃public override bool Equals(object other) { if(ReferenceEquals(null, other)) return false; if(ReferenceEquals(this, other)) return true; return this.GetHashCode() == other.GetHashCode(); }
与 GetHashCode() 分开实现 Equals
public override bool Equals(object obj) { if(ReferenceEquals(null, other)) return false; if(ReferenceEquals(this, other)) return true; var other = obj as GreaterThan32Bits; if(this.X == other.X) return this.Y == other.Y; return false; }
实现精度更高的GetHashCode64,覆盖的GetHashCode(32位)会返回(int)GetHashCode64(),Equals会返回this.GetHashCode64() == other.GetHashCode64()
你会实施哪一个?
第一个解决方案不精确,但更清洁。第二个选项看起来很干净,但是当类具有更多属性时会变得非常复杂。第三种选择是妥协。