Referans türleri için Equals() uygulaması göründüğünden daha zordur. Benim şu anki kanonik uygulaması şöyledir:Referans türleri için Equals() 'ın "en iyi" kanonik uygulaması nedir?
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();
}
Ben bu her köşesini (devralma ve gibi) durumlarda kapsar ama yanlış olabileceğini düşünüyorum. Siz ne düşünüyorsunuz?
Uygulamam "paylaşıldı". Gördüğünüz gibi, Eşittir (Object) sonunda Equals (MyClass) 'a bir çağrı var. Mutability ve GetHashCode() sorunlarının farkındayım; ama bu önemli bir gözlem. Beni birkaç kez ısırdı. Sadece "sınıflar" okuduğunu bildirmenin "kolay" bir yolu olmadığı için çok kötü. –
Bağlantı şimdilik bozuk. – Restuta