[英]extend sealed class with properties
I want to extend the Rectangle
class. 我想扩展
Rectangle
类。 Currently this class has the properties left
, right
, ... and I want to add the properties topLeft
, topRight
, ... 当前此类具有属性
left
, right
,...,我想添加属性topLeft
, topRight
,...
I know I could create some extension methods like 我知道我可以创建一些扩展方法,例如
public static Point TopLeft(this Rectangle rect)
{
return new Point(rect.Left, rect.Top);
}
but I would like to add this as a property. 但我想将此添加为属性。 I thought about inheriting from
Rectangle
and adding the missing information 我考虑过从
Rectangle
继承并添加缺少的信息
internal class Rect : Rectangle
{
public Point TopLeft
{
get
{
return new Point(X, Y);
}
}
public Point TopRight
{
get
{
return new Point(X + Width, Y);
}
}
}
but Rectangle
is a sealed class. 但是
Rectangle
是密封类。
cannot derive from sealed type 'Rectangle'
不能从密封类型“矩形”派生
So it is not possible to extend this class? 因此,不可能扩展此类吗?
You can use the adapter pattern : 您可以使用适配器模式 :
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);
}
}
}
You can't inherit from the Rectangle
but you can take it as a constructor parameter. 您不能从
Rectangle
继承,但是可以将其作为构造函数参数。 And if you don't want to override other behaviour just delegate them to Rectangle
by using _rect
, for example: 而且,如果您不想覆盖其他行为,则可以使用
_rect
将它们委托给Rectangle
,例如:
public void Intersect(Rectangle rect) => _rect.Intersect(rect);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.