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

在浏览有关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 == px) && (y == py); } 

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

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

正如其他人所说,类型可能会覆盖==运算符。 因此,转换为Object等效于if (Object.ReferenceEquals(p, null)) { ... }

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

可能存在以避免与重载的==运算符混淆。 想象一下,如果演员表不存在且==运算符超载。 现在p == null行可能绑定到operator ==。 operator ==的许多实现只是遵循重写的Equals方法。 这很容易导致堆栈溢出

 public static bool operator==(TwoDPoint left, TwoDPoint right) { return left.Equals(right); } public override bool Equals(System.Object obj) { ... TwoDPoint p = obj as TwoDPoint; if ( p == null ) { // Stack overflow!!! return false; } ... } 

通过转换为Object ,作者可以确保对null进行简单的引用检查(这是预期的)。

这可能是==运算符过载的较大样本的一部分。 在这种情况下,如果调用TwoDPoint.Equals(object)作为==定义的一部分,则使用obj == null可能导致StackOverflow。