如何解决无法从密封类继承的问题? [英] How to workaround impossible inheritance from sealed class?
问题描述
今天我正在WPF中工作.
Today im working in WPF.
我试图从System.Windows.Shapes.Line
类继承,像这样:
I tried to inherit from System.Windows.Shapes.Line
class, like this:
class MyLine : System.Windows.Shapes.Line
{
public Ln()
{
this.Stroke = Brushes.Black;
}
}
我刚刚意识到Line类是密封的.
I just realized, that Line class is sealed.
我的目标是创建一个类,该类的工作方式类似于Line
类(将其放置在Canvas
上),但是我不想每次都在其上添加画笔来弄乱我的代码,可以说总是想要黑色画笔/笔触,宽度为2px.
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.
我觉得我想做错事.
我应该怎么做?
推荐答案
您可以创建工厂类:
public class LineFactory
{
public Line Create(<parameters here>)
{
//create and return a Line object
}
}
工厂也可以是static
,但这可能会影响可测试性.
The factory could also be static
, but that could hinder testability.
请注意,此解决方案不允许您像继承那样扩展 Line
类.为此,您需要返回一个MyLine
类,该类将嵌入Line
对象以及您希望MyLine
具有的其他属性.
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; }
}
如果只是要扩展Line
类的方法,则不需要新的类,则可以在静态类中编写扩展方法:
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
}
这篇关于如何解决无法从密封类继承的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!