为什么在与null比较时转换为对象?

Thi*_*ise 17 .net c# comparison null casting

在浏览有关Equals覆盖的MSDN文档时,有一点引起了我的注意.

此特定页面的示例中,进行了一些空检查,并在进行比较时将对象转换为System.Object类型:

public override bool Equals(System.Object obj)
{
    // If parameter is null return false.
    if (obj == null)
    {
        return false;
    }

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

    // Return true if the fields match:
    return (x == p.x) && (y == p.y);
}
Run Code Online (Sandbox Code Playgroud)

有没有特定的理由使用这个演员,或者只是在这个例子中忘记了一些"无用的"代码?

Pau*_*ane 15

类型可能会使==运算符重载.强制转换为对象可确保使用原始定义.


Ste*_*ven 15

正如其他人所说,类型可能会覆盖==运算符.因此,铸造Object相当于if (Object.ReferenceEquals(p, null)) { ... }.

  • +1使用ReferenceEquals比使用者转换为对象更清晰 (4认同)

Mat*_*att 7

我相信转换为System.Object会让你解决任何运算符重载TwoDPoint可能有的问题.