在关于Equals覆盖的msdn指南中,为什么在null检查中转换为对象?
我只是在msdn上查看重载等于()的指南 (参见下面的代码); 大部分内容对我来说很清楚,但有一条线我没有得到。
if ((System.Object)p == null)
或者,在第二次覆盖中
if ((object)p == null)
为什么不简单
if (p == null)
什么是反对购买我们的演员?
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); } public bool Equals(TwoDPoint p) { // If parameter is null return false: if ((object)p == null) { return false; } // Return true if the fields match: return (x == px) && (y == py); }
可以覆盖==
运算符,如果是,则默认引用比较可能不是您得到的。 转换为System.Object可确保调用==
执行引用相等性测试。
public static bool operator ==(MyObj a, MyObj b) { // don't do this! return true; } ... MyObj a = new MyObj(); MyObj b = null; Console.WriteLine(a == b); // prints true Console.WriteLine((object)a == (object)b); // prints false
我更喜欢在这个模糊的上下文中使用object.ReferenceEquals(a, b)
来强制引用比较,因为它使得意图清晰,同时精确地保留了语义(事实上, ReferenceEquals
是这样实现的)。
我想,因为文章还讨论了覆盖operator ==,它强制它使用Object上定义的==运算符而不是当前类中的任何重载运算符。