54

ここでのSOに関する私の質問の多くは、IEquatableの実装に関するものです。ナイーブな実装には多くの隠れたバグがあり、それについて私が見つけた記事はかなり不完全であるため、正しく実装することは非常に難しいことがわかりました。私は、以下を含まなければならない決定的な参照を見つけたり、書きたいと思っています。

  • IEquatableを正しく実装する方法
  • Equalsを正しくオーバーライドする方法
  • GetHashCodeを正しくオーバーライドする方法
  • ToStringメソッドを正しく実装する方法
  • 演算子を正しく実装する方法==
  • 演算子を実装する方法!=正しく

そのような完全な参照はすでに存在しますか?

PS:MSDNリファレンスでさえ私には欠陥があるようです

4

5 に答える 5

28

IEquatable<T>値型の実装

値型の実装IEquatable<T>は、参照型の実装とは少し異なります。複素数構造体である、Implement-Your-Own-Value-Type アーキタイプがあるとします。

public struct Complex
{
    public double RealPart { get; set; }
    public double ImaginaryPart { get; set; }
}

最初のステップは、 and を実装しIEquatable<T>てオーバーライドすることです。Object.EqualsObject.GetHashCode

public bool Equals(Complex other)
{
    // Complex is a value type, thus we don't have to check for null
    // if (other == null) return false;

    return (this.RealPart == other.RealPart)
        && (this.ImaginaryPart == other.ImaginaryPart);
}

public override bool Equals(object other)
{
    // other could be a reference type, the is operator will return false if null
    if (other is Complex)
        return this.Equals((Complex)other);
    else
        return false;
}

public override int GetHashCode()
{
    return this.RealPart.GetHashCode() ^ this.ImaginaryPart.GetHashCode();
}

ほんの少しの努力で、演算子を除いて正しい実装ができました。演算子の追加も簡単なプロセスです。

public static bool operator ==(Complex term1, Complex term2)
{
    return term1.Equals(term2);
}

public static bool operator !=(Complex term1, Complex term2)
{
    return !term1.Equals(term2);
}

賢明な読者はIEquatable<double>Complex数値が基礎となる値の型と交換可能である可能性があるため、おそらく実装する必要があることに気付くでしょう。

public bool Equals(double otherReal)
{
    return (this.RealPart == otherReal) && (this.ImaginaryPart == 0.0);
}

public override bool Equals(object other)
{
    // other could be a reference type, thus we check for null
    if (other == null) return base.Equals(other);

    if (other is Complex)
    {
        return this.Equals((Complex)other);
    }
    else if (other is double)
    {
        return this.Equals((double)other);
    }
    else
    {
        return false;
    }
}

を追加する場合は 4 つの演算子が必要IEquatable<double>です。Complex == doubledouble == Complexoperator !=

public static bool operator ==(Complex term1, double term2)
{
    return term1.Equals(term2);
}

public static bool operator ==(double term1, Complex term2)
{
    return term2.Equals(term1);
}

public static bool operator !=(Complex term1, double term2)
{
    return !term1.Equals(term2);
}

public static bool operator !=(double term1, Complex term2)
{
    return !term2.Equals(term1);
}

これで、最小限の労力IEquatable<T>で、値型の正しくて便利な実装ができました。

public struct Complex : IEquatable<Complex>, IEquatable<double>
{
}
于 2009-08-20T17:48:13.070 に答える
16

オブジェクトが正しいかどうかをチェックするのと同じくらい簡単なことを実現することは、.NET の設計では少し難しいと思います。

構造体用

1) 実装しIEquatable<T>ます。パフォーマンスが著しく向上します。

2)あなたはEquals今あなた自身を持っているので、オーバーライドGetHashCodeし、さまざまな同等性チェックのオーバーライドと一貫性を保つためにobject.Equals.

3)構造体をorで意図せずに別の構造体と同一視するとコンパイラが警告するため、オーバーロード==!=演算子を宗教的に行う必要はありませんが、メソッドとの一貫性を保つためにそうすることをお勧めします。==!=Equals

public struct Entity : IEquatable<Entity>
{
    public bool Equals(Entity other)
    {
        throw new NotImplementedException("Your equality check here...");
    }

    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is Entity))
            return false;

        return Equals((Entity)obj);
    }

    public static bool operator ==(Entity e1, Entity e2)
    {
        return e1.Equals(e2);
    }

    public static bool operator !=(Entity e1, Entity e2)
    {
        return !(e1 == e2);
    }

    public override int GetHashCode()
    {
        throw new NotImplementedException("Your lightweight hashing algorithm, consistent with Equals method, here...");
    }
}

授業のために

MS から:

ほとんどの参照型は、Equals をオーバーライドする場合でも、等価演算子をオーバーロードしないでください。

私に==は、値の等価性のように感じられ、Equalsメソッドの構文糖衣のように感じられます。書くa == bことは、書くことよりもはるかに直感的ですa.Equals(b)。参照の等価性をチェックする必要があることはめったにありません。物理オブジェクトの論理表現を扱う抽象レベルでは、これを確認する必要はありません。==と のセマンティクスが異なると、Equals実際には混乱する可能性があると思います。そもそもそれは==価値の平等とEquals参照(または のようなより良い名前)の平等のためであるべきだったと思います。ここでは、MS ガイドラインを真剣に受け止めたくありません。それは、私にとって自然ではないという理由だけでなく、過負荷が大きな害を及ぼさないためでもあります。それは、非ジェネリックをオーバーライドしないのとは異なりますIsSameAs==Equalsまたは、フレームワークはどこにも使用されず、私たち自身が使用する場合にのみ使用さGetHashCodeれるため、噛み付く可能性があります。オーバーロードしない==ことで得られる唯一の本当の利点は、私が制御できないフレームワーク全体の設計との一貫性です。そして、それは確かに大きなことなので、悲しいことに私はそれに固執します.==!=

参照セマンティクス (可変オブジェクト) を使用

1) と をオーバーライドEqualsGetHashCodeます。

2) 実装IEquatable<T>は必須ではありませんが、あると便利です。

public class Entity : IEquatable<Entity>
{
    public bool Equals(Entity other)
    {
        if (ReferenceEquals(this, other))
            return true;

        if (ReferenceEquals(null, other))
            return false;

        //if your below implementation will involve objects of derived classes, then do a 
        //GetType == other.GetType comparison
        throw new NotImplementedException("Your equality check here...");
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as Entity);
    }

    public override int GetHashCode()
    {
        throw new NotImplementedException("Your lightweight hashing algorithm, consistent with Equals method, here...");
    }
}

値セマンティクス (不変オブジェクト) を使用

これはトリッキーな部分です。気をつけないと簡単にズレてしまいます..

1) と をオーバーライドEqualsGetHashCodeます。

2) オーバーロード==!=を一致させEqualsます。nulls で機能することを確認してください

2) 実装IEquatable<T>は必須ではありませんが、あると便利です。

public class Entity : IEquatable<Entity>
{
    public bool Equals(Entity other)
    {
        if (ReferenceEquals(this, other))
            return true;

        if (ReferenceEquals(null, other))
            return false;

        //if your below implementation will involve objects of derived classes, then do a 
        //GetType == other.GetType comparison
        throw new NotImplementedException("Your equality check here...");
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as Entity);
    }

    public static bool operator ==(Entity e1, Entity e2)
    {
        if (ReferenceEquals(e1, null))
            return ReferenceEquals(e2, null);

        return e1.Equals(e2);
    }

    public static bool operator !=(Entity e1, Entity e2)
    {
        return !(e1 == e2);
    }

    public override int GetHashCode()
    {
        throw new NotImplementedException("Your lightweight hashing algorithm, consistent with Equals method, here...");
    }
}

クラスを継承できる場合は、特に注意してください。そのような場合、基本クラスのオブジェクトが派生クラスのオブジェクトと等しくなるかどうかを判断する必要があります。理想的には、派生クラスのオブジェクトが等価チェックに使用されない場合、基本クラス インスタンスは派生クラス インスタンスと等価である可能性があり、そのような場合、基本クラスのTypeジェネリックで等価をチェックする必要はありません。Equals

一般に、コードを複製しないように注意してください。再利用を容易にするためのテンプレートとして、一般的な抽象基本クラス (IEqualizable<T>またはそのようなもの) を作成することもできましたが、悲しいことに C# では、追加のクラスから派生することができなくなりました。

于 2012-12-16T22:31:36.443 に答える
3

MSDN を読むと、適切な実装の最良の例がIEquatable.Equals Methodページにあると確信しています。私の唯一の逸脱は次のとおりです。

public override bool Equals(Object obj)
{
   if (obj == null) return base.Equals(obj);

   if (! (obj is Person))
      return false; // Instead of throw new InvalidOperationException
   else
      return Equals(obj as Person);   
}

偏差について疑問に思っている人のために、これはObject.Equals(Object) MSDN ページから派生しています。

Equals の実装は、例外をスローしてはなりません。

于 2009-08-20T17:07:08.347 に答える
3

別のリファレンスを見つけました。それは .NET Anonymous Type の実装です。プロパティとして int と double を持つ匿名型の場合、次の C# コードを逆アセンブルしました。

public class f__AnonymousType0
{
    // Fields
    public int A { get; }
    public double B { get; }

    // Methods
    public override bool Equals(object value)
    {
        var type = value as f__AnonymousType0;
        return (((type != null)
            && EqualityComparer<int>.Default.Equals(this.A, type.A))
            && EqualityComparer<double>.Default.Equals(this.B, type.B));
    }

    public override int GetHashCode()
    {
        int num = -1134271262;
        num = (-1521134295 * num) + EqualityComparer<int>.Default.GetHashCode(this.A);
        return ((-1521134295 * num) + EqualityComparer<double>.Default.GetHashCode(this.B);
    }

    public override string ToString()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append("{ A = ");
        builder.Append(this.A);
        builder.Append(", B = ");
        builder.Append(this.B);
        builder.Append(" }");
        return builder.ToString();
    }
}
于 2009-09-16T01:19:04.683 に答える
1

このクラスから派生するだけです

public abstract class DataClass : IEquatable<DataClass>
{
    public override bool Equals(object obj)
    {
        var other = obj as DataClass;
        return this.Equals(other);
    }

    public bool Equals(DataClass other)
    {
        return (!ReferenceEquals(null, other))
            && this.Execute((self2, other2) =>
                other2.Execute((other3, self3) => self3.Equals(other3), self2)
                , other);
    }

    public override int GetHashCode()
    {
        return this.Execute(obj => obj.GetHashCode());
    }

    public override string ToString()
    {
        return this.Execute(obj => obj.ToString());
    }

    private TOutput Execute<TOutput>(Func<object, TOutput> function)
    {
        return this.Execute((obj, other) => function(obj), new object());
    }

    protected abstract TOutput Execute<TParameter, TOutput>(
        Func<object, TParameter, TOutput> function,
        TParameter other);
}

そして、このような抽象メソッドを実装します

public class Complex : DataClass
{
    public double Real { get; set; }

    public double Imaginary { get; set; }

    protected override TOutput Execute<TParameter, TOutput>(
        Func<object, TParameter, TOutput> function,
        TParameter other)
    {
        return function(new
        {
            Real = this.Real,
            Imaginary = this.Imaginary,
        }, other);
    }
}
于 2011-12-22T14:51:39.173 に答える