Thi*_*ise 17 .net c# comparison null casting
在浏览有关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 == p.x) && (y == p.y);
}
Run Code Online (Sandbox Code Playgroud)
有没有特定的理由使用这个演员,或者只是在这个例子中忘记了一些"无用的"代码?
Ste*_*ven 15
正如其他人所说,类型可能会覆盖==运算符.因此,铸造Object相当于if (Object.ReferenceEquals(p, null)) { ... }.
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |