7
的documentation for the keyword "is"指出:的「是」關鍵字和Equals方法的重寫
的是操作者只考慮引用轉換,拳擊 轉換,和取消裝箱轉換。不考慮其他轉換,例如 用戶定義的轉換。
這是什麼意思在實踐中? 用它來檢查結構是否是某種類型是錯誤的? 例如,
public struct Point2D
{
public int X;
public int Y;
...
public override bool Equals(Object value)
{
if (value != null && value is Point2D) // or if (value != null && GetType() == value.GetType())
{
Point2D right = (Point2D)value;
return (X == right.X && Y == right.Y);
}
else return false;
}
...
}
它是錯誤的,value.GetType()== typeof(Point2D)保護您免受重構事故。 – 2012-02-08 00:59:21
是[this](http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is)的原因? – enzom83 2012-02-08 13:39:35
@ enzom83這是正確的。如果你關心從Point2D繼承,並希望孩子也擁有相同的邏輯(默認情況下),那麼'is'可能適合這種情況, – McKay 2012-02-08 16:09:35