Die Implementierung von Equals() für Referenztypen ist schwieriger als es scheint. Meine aktuelle kanonische Implementierung geht so:Was ist die "beste" kanonische Implementierung von Equals() für Referenztypen?
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();
}
Ich glaube, das gilt für alle Ecke (Vererbung und so weiter) Fälle, aber ich kann falsch sein. Was denkt ihr?
Meine Implementierung ist "geteilt". Wie Sie sehen, gibt es am Ende von Equals (Object) einen Aufruf von Equals (MyClass). Ich bin mir der Probleme mit Mutabilität und GetHashCode() bewusst; aber es ist eine wichtige Beobachtung. Es hat mich mehrmals gebissen. Schade, dass es keine "einfache" Möglichkeit gibt, nur "Klassen" zu deklarieren. –
Link ist für jetzt gebrochen. – Restuta