((System.Object)p == null)

Dan*_*ars 5 c# struct class equals

为什么这样:

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

而不是这个:

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

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

问候,

Mar*_*off 12

object当你不知道或不能确定原始类是否已被覆盖时,你会转向operator ==:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码 输出"ae is null",显然不是这种情况.演员要object避免AlwaysEqual上课operator ==,因此是真正的参考检查null.

  • 在这些情况下,我总是更喜欢`object.ReferenceEquals(obj,null)`语法.它更清楚地阐明了代码的用意. (5认同)