System.Object a = new System.Object();
System.Object b = a;
System.Object.ReferenceEquals(a, b); //returns true
- x.Equals(x) 返回 true。
- x.Equals(y) 與 y.Equals(x) 返回相同的值。
- 如果 (x.Equals(y) && y.Equals(z)) 返回 true,則 x.Equals(z) 返回 true。
- 只要不修改 x 和 y 所引用的對象,x.Equals(y) 的後續調用就返回相同的值。
- x.Equals (null) 返回 false(僅非空值類型。有關更多信息,請參見可以爲 null 的類型(C# 編程指南)。)
class TwoDPoint : System.Object
{
publicreadonly int x, y;
public TwoDPoint(int x, int y) //constructor
{
this.x = x;
this.y = y;
}
publicoverridebool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
returnfalse;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
returnfalse;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
publicbool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
returnfalse;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
publicoverride int GetHashCode()
{
return x ^ y;
}
}
class ThreeDPoint : TwoDPoint
{
publicreadonly int z;
public ThreeDPoint(int x, int y, int z)
: base(x, y)
{
this.z = z;
}
publicoverridebool Equals(System.Object obj)
{
// If parameter cannot be cast to ThreeDPoint return false:
ThreeDPoint p = obj as ThreeDPoint;
if ((object)p == null)
{
returnfalse;
}
// Return true if the fields match:
returnbase.Equals(obj) && z == p.z;
}
publicbool Equals(ThreeDPoint p)
{
// Return true if the fields match:
returnbase.Equals((TwoDPoint)p) && z == p.z;
}
publicoverride int GetHashCode()
{
returnbase.GetHashCode() ^ z;
}
}
//add this code to class ThreeDPoint as defined previously
//
publicstaticbool operator ==(ThreeDPoint a, ThreeDPoint b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
returntrue;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
returnfalse;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y && a.z == b.z;
}
publicstaticbool operator !=(ThreeDPoint a, ThreeDPoint b)
{
return !(a == b);
}
注意:
|
運算符 == 的重載中的常見錯誤是使用 (a == b)、(a == null) 或 (b == null) 來檢查引用相等性。這會調用重載的運算符 ==,從而導致無限循環。應使用 ReferenceEquals 或將類型強制轉換爲 Object 來避免無限循環。
|