我正在查看MSDN 指南中的重载等于()和运算符==的文章
我看到了以下代码
public override bool Equals(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)
奇怪的是在第二个if中投射对象
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((object)p == null)
{
return false;
}
Run Code Online (Sandbox Code Playgroud)
为什么p会再次转化为对象?写这个还不够
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if (p == null)
{
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果p不能被转换为TwoDPoint,那么它的值将为null.我很困惑,可能我不明白一些微不足道的事情......
编辑
在另一个Equals方法中再展示了一个这样的演员阵容
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,它只够检查 if(p == null)
小智 7
(object)p == null使用内置==运算符,在这种情况下检查引用相等性.p == null会调用operator==指定类型的重载.如果重载operator==将按照Equals(不是,在您链接的示例中)实现,那么您将获得无限递归.即使它没有实施Equals,它仍然需要做的不仅仅是需要做的事情.