c# - 为什么编译器至少不警告 this == null

标签 c# compiler-construction null this

为什么 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 overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.

可能会由@Aaronaught 的回应来回答。这也是为什么您应该执行 (object)x == nullReferenceEquals(x, null),而不是执行简单的 x == null,当您检查空引用时。当然,除非您确定 == 运算符没有重载。

关于c# - 为什么编译器至少不警告 this == null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2464097/

相关文章:

java - 如何从ANTLR语法中收集 'returns'

typescript - 递归应用复杂的泛型类型

C++:将 C 函数的返回值与 NULL 或 nullptr 进行比较?

c# - Json Serialize Dictionary<Enum, Int32> 的问题

c# - 剪贴板 + PresentationFramework = OutOfMemoryException?

c++ - 编译和执行 Qt 应用程序

c# - 检查 null 并在没有时分配另一个值的最短方法

c# - 如何将值传递给构造函数?

c# - 表单在 Hide() 上处理

c++ - 学习 LLVM 后端编程的代码示例