簡體   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