Skip to main content
 首页 » 编程设计

c#之我需要继承两个类(这在 C# 中是不可能的)任何人都可以推荐一种不同的方法吗

2024年02月20日13java哥

我有一个名为 WidgetBase 的抽象基类,如下所示:

public abstract class WidgetBase : Control, INamingContainer 
{ 
     // This class declares abstract and virtual properties and methods but doesn't override anything 
} 

我有另一个名为 ScrollerBase 的抽象基类,如下所示:

public abstract class ScrollerBase : Control 
{ 
    // This class has one abstract property and overrides OnInit and OnLoad 
} 

我需要创建一个继承自这两个类的类。这两个类都不能转换为接口(interface)。我能想到的最简单的解决方案是像这样创建一个额外的 WidgetBase 类:

public abstract class ScrollingWidgetBase : ScrollerBase, INamingContainer 
{ 
     // Lots of duplicated code from WidgetBase 
} 

如果我能做这样的事情就好了:

public abstract class ScrollingWidgetBase : WidgetBase<ScrollerBase>    { /* Empty */ } 
public abstract class WidgetBase : WidgetBase<Control>    { /* Empty */ } 
public abstract class WidgetBase<T> : T, INamingContainer    { /* Code goes here */ } 

但是这是不可能的。我能想到的唯一半优雅的解决方案是这样的:

public interface IScroller { /* Overridable members go here */ } 
public class WidgetBase : Control, INamingContainer 
{ 
    protected override void OnInit(EventArgs e) 
    { 
        if (this is IScroller) 
        { 
            // Do scroller logic here 
        } 
    } 
    protected override void OnLoad(EventArgs e) 
    { 
        if (this is IScroller) 
        { 
            // Do scroller logic here 
        } 
    } 
} 
 
public class Test : WidgetBase, IScroller {  } 

但是,如果创建了更多类,这会变得非常困惑。肯定有某种设计模式可以解决这个问题吗?任何帮助将不胜感激。

谢谢,

乔

请您参考如下方法:

正如 hyde 所说,您确实需要将您的行为与您的类分开。你说你不想使用接口(interface);好吧,我想不出解决办法。您可能不得不硬着头皮做一些代码重复。

至少,您可以将行为逻辑移动到一个单独的控制类,并简单地为其提供一些接口(interface)来公开所需的成员。考虑可滚动 UI 控件需要的几个属性(请注意,这只是一些例子,我怀疑这些类型是否如我所描述的那样存在,或者这些是实际的最小值 设置需要):

public interface ISCrollable 
{ 
    Control Target { get; } 
    ScrollBar Bar { get; } 
    double FullLength { get; } 
    double VisibleLength { get; } 
} 

然后您可以将您的滚动行为放在附加该行为的类中或作用于 IScrollable:

public class Scroller 
{ 
    public Scroller(ISCrollable scrollable) 
    { 
        //attach behaviour 
        scrollable.Bar.OnClick += DoScroll; 
        //and other stuff 
    } 
} 

最后,您的 ScrollableWidget 将成为您的 Control 并附加滚动行为而不是继承它:

public class ScrollableWidget : Control, INamingContainer, ISCrollable, IWidget 
{ 
    private Scroller ScrollBehaviour; 
    private Widgeter = WidgetBehaviour; 
 
    public Control Target { get; private set; } 
    public ScrollBar Bar { get; private set; } 
    public double FullLength { get; private set; } 
    public double VisibleLength { get; private set; } 
 
    public ScrollableWidget() 
    { 
        this.Target = this; 
        this.Bar = CreateScrollBarControl(); 
        this.FullLength = 9001; 
        this.VisibleLength = this.ActualHeight; 
 
        this.ScrollBehaviour = new Scroller(this); 
        this.WidgetBehaviour = new Widgeter(this); 
    } 
} 

是的,您将要使用接口(interface)。我不明白你的要求不要。还有其他模式,例如 Decorator ,这可能比我刚刚发布的困惑更适合。