铸造对象为null检查之前,在覆盖的Equals [英] Cast to object before null check in overriding Equals
本文介绍了铸造对象为null检查之前,在覆盖的Equals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
刚刚看完MSDN文章重写等式运算符这里
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;
}
为什么会出现强制转换为对象
这里执行空
比较呢?
推荐答案
运营商申请通过静态分析(和过载),而不是虚方法(覆盖)。跟投,这是做一个参考平等检查。如果不投,它可以运行 TwoDPoint
运营商。我想这是为了避免当加入运营商的问题。
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.
就个人而言,虽然,我会做一个参考检查明确与的ReferenceEquals
。
Personally, though, I'd do a reference check explicitly with ReferenceEquals
.
这篇关于铸造对象为null检查之前,在覆盖的Equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文