为引用类型实现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();
}
Run Code Online (Sandbox Code Playgroud)
我认为这涵盖了所有角落(继承等),但我可能错了.你们有什么感想?
小智 4
我不久前为此写了一份相当全面的指南。首先,您的 equals 实现应该是共享的(即,采用对象的重载应该传递给采用强类型对象的重载)。此外,您还需要考虑一些事情,例如您的对象应该是不可变的,因为需要重写 GetHashCode。更多信息请点击这里:
http://gregbeech.com/blog/implementing-object-equality-in-dotnet
| 归档时间: |
|
| 查看次数: |
1149 次 |
| 最近记录: |