问题描述
为什么C#编译器甚至没有对这些代码的警告抱怨吗?
Why does the C# compiler not even complain with a warning on this code? :
if (this == null)
{
// ...
}
显然病情会的从不满意..
Obviously the condition will never be satisfied..
推荐答案
因为你可以的为这种情况下返回true。
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;
}
}
运行新富() 。。测试()
将打印真到控制台
这里的另一个问题是:为什么不编译器发出警告为的ReferenceEquals(这一点,空)
?从上面的链接的底部:
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 == b)
,(一== NULL)
或(二== NULL)
检查引用相等。这反而会导致对重载运算符==
通话,造成一个无限循环。使用的ReferenceEquals
或转换为对象,以避免循环的类型。
的这的可能被@ Aaronaught的回应回答。这也是为什么你应该做(对象)x == NULL
或的ReferenceEquals(X,NULL)
,不做一个简单的 X == NULL ,当你检查空引用。当然,除非,你是确保 ==
运营商不会过载。
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.
这篇关于为什么没有编译器,至少在这个== NULL警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!