How to workaround impossible inheritance from sealed class?

让人想犯罪 __ 提交于 2019-12-10 17:24:21

问题


Today im working in WPF.

I tried to inherit from System.Windows.Shapes.Line class, like this:

class MyLine : System.Windows.Shapes.Line
{
    public Ln()
    {
        this.Stroke = Brushes.Black;
    }
}

I just realized, that Line class is sealed.

My goal is to create a class, that will work like Line class (to put it on Canvas), but I don't want to mess my code with adding brush to it everytime, lets say always want black brush/stroke with 2px width.

I feel im trying to do it wrong.

How should I do that?


回答1:


You could create a factory class:

public class LineFactory
{
    public Line Create(<parameters here>)
    {
        //create and return a Line object
    }
}

The factory could also be static, but that could hinder testability.

Note that this solution doesn't let you extend the Line class as inheritance would. To do that you would need to return a MyLine class which would embed a Line object along with the additional properties you'd want MyLine to have.

public class MyLine
{
    private Line _theBoringOriginal; // composition: "has-a" (vs inheritance "is-a")
    public MyLine(Line line)
    {
        _theBoringOriginal = line;
    }

    public foo SomeProperty { get; set; }
}

If it's just methods you want to extend the Line class with, you don't need a new class, you could just write extension methods in a static class:

public static foo DoSomethingCool(this Line line, <parameters here>)
{
    // whatever
}



回答2:


Why not simply create an extension class to do what you want? Extension classes were create specifically to allow you to extend sealed classes with new methods, without having to actually inherit things.

public static class LineExtensions {
    // returns the Line so you can use it fluently
    public static Line MakeLineBlack(this Line line) {
        line.Stroke = Brushes.Black;
        return line;
    }
}

Then you can just do this:

var line = new Line().MakeLineBlack();


来源:https://stackoverflow.com/questions/16745476/how-to-workaround-impossible-inheritance-from-sealed-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!