在Equals覆盖中浏览MSDN文档时,有一点引起了我的注意。为什么要比较null时将对象转换为对象?
论this specific page的例子,一些空的检查是由,和做比较,当对象被浇铸成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);
}
是否有使用该投一个具体的理由,或这只是在这个例子中被遗忘的一些“无用的”代码?
因此使得exmaple代码安全复制和粘贴。 – 2010-08-04 15:35:13