为什么 C# 编译器甚至不对这段代码发出警告? :
if (this == null)
{
// ...
}
显然条件永远不会被满足..
最佳答案
因为你可以 override operator ==
在这种情况下返回 true。
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;
}
}
运行 new Foo().Test()
将在控制台打印“True”。
这里的另一个问题是:为什么编译器不对 ReferenceEquals(this, null)
发出警告?从上面链接的底部:
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 overloadedoperator ==
, causing an infinite loop. UseReferenceEquals
or cast the type to Object, to avoid the loop.
那 可能会由@Aaronaught 的回应来回答。这也是为什么您应该执行 (object)x == null
或 ReferenceEquals(x, null)
,而不是执行简单的 x == null
,当您检查空引用时。当然,除非您确定 ==
运算符没有重载。
关于c# - 为什么编译器至少不警告 this == null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2464097/