Реализация 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();
}
Я думаю, что это охватывает весь угол (наследование и такие) дела, но я могу ошибаться. Ребята, что вы думаете?
Я знаю, что реализация для типов значений отличаются. Я спрашивал о ссылочных типах. – 2008-09-16 19:04:22
Сломанная ссылка. : | – Restuta 2012-02-15 07:53:34
Я исправил неработающую ссылку ... – 2012-02-22 22:39:52