.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() を返します。
どれを実装しますか?
最初の解決策は不正確ですが、よりクリーンです。2 番目のオプションはきれいに見えますが、クラスのプロパティが増えると非常に複雑になります。3 番目のオプションは妥協です。