リファレンスタイプのEquals()の実装は、それよりも難しくなります。私の現在の標準的な実装では、このように書きます:参照型のためのEquals()の "最良の"正規の実装は何ですか?
public bool Equals(MyClass obj)
{
// If both refer to the same reference they are equal.
if(ReferenceEquals(obj, this))
return true;
// If the other object is null they are not equal because in C# this cannot be null.
if(ReferenceEquals(obj, null))
return false;
// Compare data to evaluate equality
return _data.Equals(obj._data);
}
public override bool Equals(object obj)
{
// If both refer to the same reference they are equal.
if(ReferenceEquals(obj, this))
return true;
// If the other object is null or is of a different types the objects are not equal.
if(ReferenceEquals(obj, null) || obj.GetType() != GetType())
return false;
// Use type-safe equality comparison
return Equals((MyClass)obj);
}
public override int GetHashCode()
{
// Use data's hash code as our hashcode
return _data.GetHashCode();
}
私は、これはすべてのコーナー(相続など)のケースをカバーしていますが、私は間違っているかもしれだと思います。皆さんはどう思いますか?
私の実装は "共有"です。ご覧のように、Equals(Object)の最後にはEquals(MyClass)が呼び出されます。 私はmutabilityとGetHashCode()の問題を認識しています。それは重要な観察です。それは私に何度か噛み付いている。読み込み専用の "クラス"を宣言する "簡単な"方法はないというのは残念です。 –
リンクは現在壊れています。 – Restuta