我在看从MSDN Guidelines for Overloading Equals() and Operator ==中值为奇怪铸覆盖由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);
}
奇怪的是在第二,如果
反对投// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((object)p == null)
{
return false;
}
为什么p再次铸造对象?是不是足够写这
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if (p == null)
{
return false;
}
如果p不能铸造TwoDPoint,那么它的值将为空。我百思不得其解,大概我不明白一些小事...
编辑
另外一个此类铸件呈现在其他equals方法
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
}
这里再次这足以检查只有if(p == null)
这是一个代码味道。他们应该使用ReferenceEquals。 – usr