[英]extend sealed class with properties
我想擴展Rectangle
類。 當前此類具有屬性left
, right
,...,我想添加屬性topLeft
, topRight
,...
我知道我可以創建一些擴展方法,例如
public static Point TopLeft(this Rectangle rect)
{
return new Point(rect.Left, rect.Top);
}
但我想將此添加為屬性。 我考慮過從Rectangle
繼承並添加缺少的信息
internal class Rect : Rectangle
{
public Point TopLeft
{
get
{
return new Point(X, Y);
}
}
public Point TopRight
{
get
{
return new Point(X + Width, Y);
}
}
}
但是Rectangle
是密封類。
不能從密封類型“矩形”派生
因此,不可能擴展此類嗎?
您可以使用適配器模式 :
internal class RectAdapter
{
private Rect _rect;
public RectAdapter(Rectangle rect)
{
_rect = rect;
}
public Point TopLeft
{
get
{
return new Point(_rect.X, _rect.Y);
}
}
public Point TopRight
{
get
{
return new Point(_rect.X + _rect.Width, _rect.Y);
}
}
}
您不能從Rectangle
繼承,但是可以將其作為構造函數參數。 而且,如果您不想覆蓋其他行為,則可以使用_rect
將它們委托給Rectangle
,例如:
public void Intersect(Rectangle rect) => _rect.Intersect(rect);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.