在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