譬如說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)));
}
慣於如果`對象obj`是一個結構這炸燬? – row1 2013-01-08 13:29:16