在重写 Equals 中进行 null 检查之前转换为对象
只需在此处阅读有关覆盖相等运算符的 msdn 文章
以下代码片段让我感到困惑...
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null) // <-- wtf?
{
return false;
}
为什么这里要强制转换为 Object
来执行 null
比较?
Just reading the msdn article on overriding equality operators here
The following snippet confuses me...
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null) // <-- wtf?
{
return false;
}
Why is there a cast to Object
here to perform the null
comparison?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
运算符通过静态分析(和重载)而不是虚拟方法(覆盖)来应用。通过强制转换,它正在执行引用相等性检查。如果没有强制转换,它可以运行
TwoDPoint
运算符。我想这是为了避免添加运算符时出现问题。不过,就我个人而言,我会使用
ReferenceEquals
显式进行引用检查。Operators apply through static analysis (and overloads), not virtual methods (overrides). With the cast, it is doing a reference equality check. Without the cast, it can run the
TwoDPoint
operator. I guess this is to avoid problems when an operator is added.Personally, though, I'd do a reference check explicitly with
ReferenceEquals
.不!如果您不这样做,运行时将开始对您所在的相等运算符进行递归调用,这会导致无限递归,从而导致堆栈溢出。
No! if you don't do that, the runtime will start a recursive call to the equality operator you are just in which results in infinite recursion and, consequently, a stack overflow.
强制它使用 Object 的 Equals 方法而不是它自己的重载版本......只是一个猜测......
To force it to use the Equals method of Object rather than its own overloaded version... just a guess...
这并非无用。如果没有这种转换,重载的 == 运算符将被递归调用......
This is not useless. Without that cast the == operator being overloaded would be called recursively...
下面是执行强制转换的行,
与“正常”强制转换的区别在于,如果对象不是“可强制转换”,则使用“As”不会引发异常。在这种情况下,如果“p”不是
TwoDPoint
类型,则不会引发异常(转换无效),而是返回 null。此代码检查强制转换是否正常,如果不是,则由于上述原因 p 应该为 null
the below is the line that does the cast
the difference with the "normal" cast is that using "As" it doesn't raise an exception if the object is not "castable". In this case if "p" is not a
TwoDPoint
Type is not gonna raise an exception (cast not valid) but return null.this code check if the cast went fine if not p should be null for the reason above
请注意,这是 VS 2005 文档。我想编写文档的人也有同样的问题,但无法给出一个好的答案;该示例针对 VS 2008 进行了更改。这是 当前版本:
Note that this is the VS 2005 documentation. I guess the folks who write the documentation also had the same question and couldn't come up with a good answer; the example was changed for VS 2008. Here is the current version: