gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:07:40 26 4
gpt4 key购买 nike

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

我想为这些类添加自定义功能,例如(读取、警报等)这些添加的功能在所有这些类中都是相同的

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

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

  • 重复每个继承的代码类

  • 使用一个单独的类作为静态方法的功能使用来自接口(interface)的参数,为类实现此接口(interface),并且然后通过它们。

  • 像第二种方法一样使用单独的类,但使用动态参数(在 C# 4.0 中添加)

    或其他!!

提前致谢

最佳答案

我会考虑选项 4:组合。

首先,定义您的功能集。我们假设您的部分列表是排他性的,因此“阅读”和“提醒”。

其次,创建一个实现此功能的类,例如 MyCommonControlBehaviors。如果可能的话,我希望这个实现不是静态的,尽管它可能是通用的。

public MyCommonControlBehaviors
{
public Whatever Read() { /* ... */ }
public void Alert() {}
}

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

public class MyCustomControl
{
private MyCommonControlBehaviors common; // Composition

public Whatever Read() { return this.common.Read(); }
public void Alert() { this.common.Alert(); }
}

根据具体情况,您可以根据需要发挥创意。例如,您的自定义行为可能需要与私有(private)控制数据进行交互。在这种情况下,让您的控件实现您的常见行为所需的通用 ICommonBehaviorHost 接口(interface)。然后将控件作为 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 */ }
}

关于c# - C# 中多重继承的替代解决方案的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3055067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com