Because you could override operator ==
to return true for that case.
public class Foo
{
public void Test()
{
Console.WriteLine(this == null);
}
public static bool operator ==(Foo a, Foo b)
{
return true;
}
public static bool operator !=(Foo a, Foo b)
{
return true;
}
}
Running new Foo().Test()
will print "True" to the console.
The other question here is: why doesn't the compiler issue a warning for ReferenceEquals(this, null)
? From the bottom of the above link:
A common error in overloads of operator ==
is to use (a == b)
, (a == null)
, or (b == null)
to check for reference equality. This instead results in a call to the overloaded operator ==
, causing an infinite loop. Use ReferenceEquals
or cast the type to Object, to avoid the loop.
That might be answered by @Aaronaught's response. And that's also why you should be doing (object)x == null
or ReferenceEquals(x, null)
, not doing a simple x == null
, when you're checking for null references. Unless, of course, you're sure that the ==
operator is not overloaded.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…