接口和继承

本文关键字:继承 接口 | 更新日期: 2023-09-27 17:56:17

C#, VS 2008我有 4 种情况,比如 a、b、c、d,我计划将它们分开并创建单独的类这 4 种情况有一些共同点,我将它们放在一个接口中并创建一个实现该接口的基类。 现在A&B,A&C,C&D之间有一些共同点,不确定如何制作一个好的/干净的工具。

谢谢

接口和继承

有几个选项。

你可以让 c 和 d 从 a 继承,d 从 c 继承。您可以为每个对 a/b、a/c 和 c/d 创建一个基类。您可以复制功能。您可以通过帮助程序类提供该功能(静态方法可能是一个选项)。

这实际上取决于共享的功能以及类的预期用途。

这取决于常见事物的工作方式以及它们如何与私有/受保护的数据相关联和使用,但通常组合可以是继承的补充或替代方案。

公共部分分解为您从 a、b、c 和 d 的不同实现中使用的帮助程序类。

仅当实现未与每个类的私有数据紧密耦合时,这才有可能。

作为一般规则,仅当对象是同一对象的不同类型时,才应使用继承。如果是这种情况,则可以使用继承来共享基对象定义中固有的实现。

如果类 a、b、c 和 d 并不是同一对象的不同类型,那么您可以尝试将它们的公共功能封装在内部引用的对象中。

public class a
{
    private CommonFunctionalityClass commonFunc;
    public a()
    {
        this.commonFunc = new CommonFunctionalityClass();
    }
} 

当你想做一些常见的事情时,你只需调用你的commonFunc实例。您可以对 a/b、b/c 和 c/d 执行相同的封装,其中您通过使用内部引用的对象通过 具有关系共享功能。这样,您就不会复制代码,但可以灵活地共享功能。

public interface IABInterface
{
    //Whatever is common to A and B. It will have to be implemented in the classes
}
public interface IACInterface
{
    //Whatever is common to A and C. It will have to be implemented in the classes
}
public interface ICDInterface
{
    //Whatever is common to C and D. It will have to be implemented in the classes
}
public class ABCDBase
{
    //Whatever is common to all classes
}
public class A : ABCDBase, IABInterface, IACInterface
{
}
public class B : ABCDBase, IABInterface
{
}
public class C : ABCDBase, IACInterface, ICDInterface
{
}
public class D : ABCDBase, ICDInterface
{
}

您可以稍后在静态类扩展中为接口创建方法,以便不复制接口实现中方法的代码(换句话说,不要在接口中定义方法,只定义属性)。通过重构,在接口中实现属性非常容易。最好有扩展属性。对未来充满希望。

编辑

喜欢这个:

public static class Helper
{
    public static void IABMethod1(this IABInterface aOrBObject, arguments args)
    {
        //This will be available for any A or B object without duplicating any code
    }
}