为什么在与 null 比较时强制转换为对象?
在浏览有关 Equals 覆盖的 MSDN 文档时,有一点引起了我的注意。
在此特定页面的示例中,一些进行 null 检查,并且在进行比较时将对象强制转换为 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);
}
是否有使用此强制转换的特定原因,或者只是在本示例中忘记了一些“无用”代码?
While browsing the MSDN documentations on Equals overrides, one point grabbed my attention.
On the examples of this specific page, some null checks are made, and the objects are casted to the System.Object type when doing the comparison :
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);
}
Is there a specific reason to use this cast, or is it just some "useless" code forgotten in this example ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我相信转换为 System.Object 可以让您绕过 TwoDPoint 可能具有的任何运算符重载。
I believe casting to System.Object would get you around any operator overloading that TwoDPoint might have.
它的存在可能是为了避免与重载的 == 运算符混淆。想象一下,如果强制转换不存在并且 == 运算符被重载。现在,
p == null
行可能会绑定到运算符 ==。许多运算符 == 的实现只是遵循重写的Equals
方法。这很容易导致堆栈溢出情况通过转换为
Object
,作者确保对null
进行简单的引用检查(这正是预期的目的)。It likely exists to avoid confusion with an overloaded == operator. Imagine if the cast did not exist and the == operator was overloaded. Now the
p == null
line would potentially bind to the operator ==. Many implementations of operator == simply defer to the overriddenEquals
method. This could easily cause a stack overflow situationBy casting to
Object
the author ensures a simple reference check fornull
will occur (which is what is intended).这可能是 == 运算符重载的较大示例的一部分。在这种情况下,如果将 TwoDPoint.Equals(object) 作为 == 定义的一部分调用,则使用 obj == null 可能会导致 StackOverflow。
This might have been part of a larger sample where the == operator was overloaded. In that case, using obj == null could have resulted in StackOverflow if TwoDPoint.Equals(object) was invoked as part of the == definition.
类型可能会重载 == 运算符。转换为对象可确保使用原始定义。
It is possible for a type to overload the == operator. The cast to object ensures that the original definition is used.
正如其他人所说,类型可能会覆盖 == 运算符。因此,转换为
Object
相当于if (Object.ReferenceEquals(p, null)) { ... }
。As others said, the type might override the == operator. Therefore, casting to
Object
is equivalent toif (Object.ReferenceEquals(p, null)) { ... }
.