I was just looking at the Guidelines for Overloading Equals() on msdn (see code below); most of it is clea开发者_运维问答r to me, but there is one line I don't get.
if ((System.Object)p == null)
or, in the second override
if ((object)p == null)
Why not simply
if (p == null)
What is the cast to object buying us?
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
The ==
operator may be overridden, and if it is, the default reference comparison may not be what you get. Casting to System.Object ensures that calling ==
performs a reference equality test.
public static bool operator ==(MyObj a, MyObj b)
{
// don't do this!
return true;
}
...
MyObj a = new MyObj();
MyObj b = null;
Console.WriteLine(a == b); // prints true
Console.WriteLine((object)a == (object)b); // prints false
I prefer using object.ReferenceEquals(a, b)
in this ambiguous context to force reference comparison because it makes the intent clear while preserving the semantics precisely (in fact, ReferenceEquals
is implemented like that).
I suppose, since the article also talks about overriding operator==, that it's forcing it to use the == operator defined on Object rather than any overloaded operator in the current class.
精彩评论