C# 用属性扩展密封类
我想扩展C# 用属性扩展密封类,c#,C#,我想扩展矩形类。当前,此类的属性为左,右。。。我想添加属性左上,右上 我知道我可以创建一些扩展方法,比如 public static Point TopLeft(this Rectangle rect) { return new Point(rect.Left, rect.Top); } 但我想把它作为一个属性。我考虑从Rectangle继承并添加缺少的信息 internal class Rect : Rectangle { public Point TopLeft {
矩形
类。当前,此类的属性为左
,右
。。。我想添加属性左上
,右上
我知道我可以创建一些扩展方法,比如
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
是一个密封类
无法从密封类型“矩形”派生
因此无法扩展此类?您可以使用:
不能从矩形继承,但可以将其作为构造函数参数。如果您不想覆盖其他行为,只需使用\u rect
将它们委托给矩形,例如:
public void Intersect(Rectangle rect) => _rect.Intersect(rect);
rect.Location
用于rect.TopLeft
和rect.Location+rect.Size
用于rect.BottomRight
密封的
。因此,目前的答案是不可能的,至少在我们得到答案之前是不可能的,希望是在C#8中。
public void Intersect(Rectangle rect) => _rect.Intersect(rect);