我想扩展Rectangle课程.目前,这个类的属性left,right......我想添加的属性topLeft,topRight...
我知道我可以创建一些扩展方法,如
public static Point TopLeft(this Rectangle rect)
{
return new Point(rect.Left, rect.Top);
}
Run Code Online (Sandbox Code Playgroud)
但我想将此作为财产添加.我想过继承Rectangle和添加缺少的信息
internal class Rect : Rectangle
{
public Point TopLeft
{
get
{
return new Point(X, Y);
}
}
public Point TopRight
{
get
{
return new Point(X + Width, Y);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您不能继承,Rectangle但可以将其作为构造函数参数.如果您不想覆盖其他行为,只需Rectangle使用它们委托它们_rect,例如:
public void Intersect(Rectangle rect) => _rect.Intersect(rect);
Run Code Online (Sandbox Code Playgroud)