c# - ((System.Object)p == null)

标签 c# class struct equals

为什么这样做:

    // If parameter cannot be cast to Point return false.
    TwoDPoint p = obj as TwoDPoint;
    if ((System.Object)p == null)
    {
        return false;
    }

取而代之的是:

    // If parameter cannot be cast to Point return false.
    TwoDPoint p = obj as TwoDPoint;
    if (p == null)
    {
        return false;
    }

我不明白你为什么要写 ((System.Object)p)?

问候,

最佳答案

当你不知道或不能确定原始类是否覆盖了operator ==时,你转换为object:

using System;
class AlwaysEqual
{
    public static bool operator ==(AlwaysEqual a, AlwaysEqual b)
    {
        return true;
    }

    public static bool operator !=(AlwaysEqual a, AlwaysEqual b)
    {
        return true;
    }
}


class Program
{
    static void Main()
    {
        object o = new AlwaysEqual();
        AlwaysEqual ae = o as AlwaysEqual;

        if (ae == null)
        {
            Console.WriteLine("ae is null");
        }

        if ((object)ae == null)
        {
            Console.WriteLine("(object)ae is null");
        }
    }
}

这段代码只输出 “ae is null”,显然不是这样的。转换为 object 避免了 AlwaysEqual 类的 operator ==,因此是针对 null 的真正引用检查。

关于c# - ((System.Object)p == null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2908702/

相关文章:

c - 尝试将整个结构从最高等级排序到最低等级

c - 为什么位字段的类型会影响包含结构的大小?

c# - 组合 2 个 linq 操作

java - 使用多个类时未定义构造函数

javascript - 在类中使用 async await 来分配属性但返回 null

javascript - 如何检测 javascript 中链接的类别?

c# - 将带有字符串的 C# 结构传递给 C++ 应用程序

java - 等价于 c# 中的 matcher.start 和 matcher.end

c# - 通过由特定形式的 onclick 识别的 webBrowser 按下网站上的按钮

c# - 如何读取 MVC Controller 方法中的 web.config 设置并在 angularjs View 、 Controller 和服务中访问它们?