多くの IEqualityComparers の実装にやや怠惰であり、比較対象のオブジェクトのクラス実装を簡単に編集できないことを考えると、Distinct() および Except() 拡張メソッドで使用することを意図した次の方法を使用しました。:
public class GenericEqualityComparer<T> : IEqualityComparer<T>
{
Func<T, T, bool> compareFunction;
Func<T, int> hashFunction;
public GenericEqualityComparer(Func<T, T, bool> compareFunction, Func<T, int> hashFunction)
{
this.compareFunction = compareFunction;
this.hashFunction = hashFunction;
}
public bool Equals(T x, T y)
{
return compareFunction(x, y);
}
public int GetHashCode(T obj)
{
return hashFunction(obj);
}
}
いいように思えますが、本当に必要なたびにハッシュ関数を与えることはありますか? オブジェクトをバケットに入れるためにハッシュコードが使用されることを理解しています。異なるバケット、オブジェクトは等しくなく、equal は呼び出されません。
GetHashCode が同じ値を返す場合、equals が呼び出されます。( from : Equals メソッドがオーバーライドされたときに GetHashCode をオーバーライドすることが重要なのはなぜですか? )
では、たとえば (多くのプログラマーが恐怖で叫んでいるのを聞いています)、 GetHashCode が定数を返し、 Equal の呼び出しを強制する場合、何が問題になる可能性がありますか?