假设我有一个Point2类,我想实现以下Equals:
public override bool Equals ( object obj )
public bool Equals ( Point2 obj )
这来自有效的C#3书:
public override bool Equals ( object obj )
{
// STEP 1: Check for null
if ( obj == null )
{
return false;
}
// STEP 3: equivalent data types
if ( this.GetType ( ) != obj.GetType ( ) )
{
return false;
}
return Equals ( ( Point2 ) obj );
}
public bool Equals ( Point2 obj )
{
// STEP 1: Check for null if nullable (e.g., a reference type)
if ( obj == null )
{
return false;
}
// STEP 2: Check for ReferenceEquals if this is a reference type
if ( ReferenceEquals ( this, obj ) )
{
return true;
}
// STEP 4: Possibly check for equivalent hash codes
if ( this.GetHashCode ( ) != obj.GetHashCode ( ) )
{
return false;
}
// STEP 5: Check base.Equals if base overrides Equals()
System.Diagnostics.Debug.Assert (
base.GetType ( ) != typeof ( object ) );
if ( !base.Equals ( obj ) )
{
return false;
}
// STEP 6: Compare identifying fields for equality.
return ( ( this.X.Equals ( obj.X ) ) && ( this.Y.Equals ( obj.Y ) ) );
}
这有点矫枉过正吗?
答案 0 :(得分:3)
支持与继承层次结构的相等性是棘手的。你需要弄清楚你的意思。你真的需要继承吗?如果不是 - 如果Point2直接从System.Object派生,并且你可以使它密封,生活变得容易一些。在那种情况下,我会使用:
public override bool Equals (object obj)
{
return Equals(obj as Point2);
}
public bool Equals (Point2 obj)
{
// STEP 1: Check for null if nullable (e.g., a reference type)
// Note use of ReferenceEquals in case you overload ==.
if (object.ReferenceEquals(obj, null))
{
return false;
}
// STEP 2: Check for ReferenceEquals if this is a reference type
// Skip this or not? With only two fields to check, it's probably
// not worth it. If the later checks are costly, it could be.
if (object.ReferenceEquals( this, obj))
{
return true;
}
// STEP 4: Possibly check for equivalent hash codes
// Skipped in this case: would be *less* efficient
// STEP 5: Check base.Equals if base overrides Equals()
// Skipped in this case
// STEP 6: Compare identifying fields for equality.
// In this case I'm using == instead of Equals for brevity
// - assuming X and Y are of a type which overloads ==.
return this.X == obj.X && this.Y == obj.Y;
}
答案 1 :(得分:2)
不是真的 - 你几乎考虑到了所有可能性。如果此代码用于除临时应用程序之外的任何其他内容,则应考虑此方法的好处,因为由于奇怪的对象相等行为导致的逻辑错误很难调试。
答案 2 :(得分:1)
让我觉得你想要什么。整个区块归结为:
“如果它是完全相同的实例,则返回true。如果它们是具有相同X和Y值的单独实例,则返回true。所有其他情况(null,不同类型,不同x / y值)返回false。”
答案 3 :(得分:1)
它的代码肯定比我想要为equals方法编写的代码更多。有很多冗余检查,例如检查ReferenceEquals和HashCodes(我知道这些检查是多余的,因为函数中的最后一行检查结构相等性)。专注于简单易读的代码。
public bool Equals(object o)
{
Point2 p = o as Point2;
if (o != null)
return this.X == o.X && this.Y == o.Y;
else
return false;
}
由于您的equals方法使用结构相等,因此请确保使用基于您的字段的实现覆盖GetHashCode。