C#中多重继承的替代解决方案的最佳实践是什么?

Hom*_*mam 5 c# oop inheritance

我有一些类继承自现有的Windows控件,如TextBox和DateTimePicker,.. iec

我想为这些类添加自定义功能,如(Read,Alert,...等)这些添加的功能在所有这些类中都是相同的

问题是:这些类继承自不同的父类,所以我不能将我添加的功能放在父类中,

在这种情况下,最佳做法是什么:

  • 重复每个继承类中的代码

  • 使用一个分离的类具有静态方法的功能和接口的参数,为类实现此接口,然后传递它们.

  • 像第二种方法一样使用分离的类,但使用Dynamic参数(在C#4.0中添加)

    或其他 !!

提前致谢

Gre*_*g D 12

我会考虑选项4:组合.

首先,定义您的功能集.我们假设您的部分列表是独占的,因此"读取"和"警报".

其次,创建一个实现此功能的类,类似于MyCommonControlBehaviors.如果可能的话,我希望这个实现不是静态的,但它可能是通用的.

public MyCommonControlBehaviors
{
    public Whatever Read() { /* ... */ }
    public void Alert() {}
}
Run Code Online (Sandbox Code Playgroud)

第三,使用组合将此类的实例添加到每个自定义控件类型,并通过自定义控件公开该功能:

public class MyCustomControl
{
    private MyCommonControlBehaviors common; // Composition

    public Whatever Read() { return this.common.Read(); }
    public void Alert() { this.common.Alert(); }
}
Run Code Online (Sandbox Code Playgroud)

根据具体情况,您可以获得必要的创意.例如,您的自定义行为可能需要与私有控制数据进行交互.在这种情况下,使您的控件实现一个ICommonBehaviorHost您的常见行为所需的通用接口.然后将控件传递给构造中的行为类作为以下实例ICommonBehaviorHost:

public interface ICommonBehaviorHost
{
    void Notify();
}

public class MyCommonControlBehaviors
{
    ICommonBehaviorHost hst = null;

    public MyCommonControlBehaviors(ICommonBehaviorHost host) 
    {
        this.hst = host;
    }

    public void Alert() { this.hst.Notify(); }  // Calls back into the hosting control
    // ...
}

public class MyCustomControl : ICommonBehaviorHost
{
    private MyCommonControlBehaviors common = null;

    public MyCustomControl() { common = new MyCommonControlBehaviors(this); }
    public Whatever Read() { return this.common.Read(); }
    public void Alert() { this.common.Alert(); }

    void ICommonBehaviorHost.Notify() { /* called by this.common */ }
}
Run Code Online (Sandbox Code Playgroud)

  • 并将其与依赖注入相结合,以最大限度地减少系统的耦合...... (4认同)