繁体   English   中英

用属性扩展密封类

[英]extend sealed class with properties

我想扩展Rectangle类。 当前此类具有属性leftright ,...,我想添加属性topLefttopRight ,...

我知道我可以创建一些扩展方法,例如

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM