C#中的多重继承:实现我想要做的事情的纯粹方式是什么?

Nic*_*ick 5 .net c#

我确实理解C#中没有多重继承.但是,我遇到了一种我真的希望它存在的情况.我正在创建一个自定义类,它要求我继承CLR类型并覆盖一些方法.不幸的是,我正在创建其中几个非常相似的.为了DRY的利益,我真的想将常用功能移到基类,但后来我需要继承2个类.我可以使用接口(事实上我现在正在使用它)但这只解决了一半的问题,因为方法实现仍然需要在几个自定义类中重复.

实现我想要做的事情的纯粹方式是什么?

编辑:

这是一个通用的代码示例

public class CustomTypeOne : CLRType
{
   public override void Execute(HttpContext context)
   {
        //Some code that's similar across CustomTypeOne, CustomTypeTwo etc
   }

   public void DoStuff()
   {
       //Same for all CustomTypes and can be part of a base class
   }

   //More methods
}

public class CustomTypeTwo : CLRType
{
   public override void Execute(HttpContext context)
   {
        //Some code that's similar across CustomTypeOne, CustomTypeTwo etc
   }

   public void DoStuff()
   {
       //Same for all CustomTypes and can be part of a base class
   }

   //More methods

}
Run Code Online (Sandbox Code Playgroud)

spo*_*son 10

在我觉得多重继承可以节省一天的时候,我意识到它确实使实现和可维护性更具挑战性.MI有效地将公共命名空间和受保护的命名空间合并到继承的类中,这可能会导致您不需要的模糊性和复杂性.

因此,通常我更乐意实施HAS-A关系,而不是IS -A关系.我将继承的类将是类中的数据成员.


Dev*_*inB 2

有几种方法可以实现您所说的内容。

假设你有一个像这样的结构

MyTypeA : CLR_TypeA
{
    public override ToString()
    {
       //do some complicated stuff
    }
}
MyTypeB : CLR_TypeB
{
    public override ToString()
    {
       //do the same complicated stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

那么想要有一个基类是有道理的,但你不能。其他答案提到的一种方法是组合。但是,在您的情况下,可能可以创建另一个静态类

public static class ToStringHelpers
{
    public static DoComplicatedStuff()
    {
       //do some pretty wild stuff.
    }
}

MyTypeA : CLR_TypeA
{
    public override ToString()
    {
       DoComplicatedStuff();
    }
}
MyTypeB : CLR_TypeB
{
    public override ToString()
    {
       DoComplicatedStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,所有需要重复功能的不同对象都可以调用辅助方法。在这种情况下,多重继承的唯一优点是您不必一遍又一遍地编写“DoComplicatedStuff()”,但复制/粘贴无论如何都会很快解决该问题。

编辑

如果您从同一类型继承,则不需要 MI

MyBaseType : CLRType
{
   public override void Execute(HttpContext context)
   {
       //Some code that's similar across CustomTypeOne, CustomTypeTwo etc
   }

   public void DoStuff()
   {
      //Same for all CustomTypes and can be part of a base class
   }

}

MyTypeA : MyBaseType
{
    public void MyTypeACustomMethod()
    { 
      //do class specific logic here
    }
}

MyTypeB : MyBaseType
{
    public void MyTypeBCustomMethod()
    { 
      //do class specific logic here
    }
}
Run Code Online (Sandbox Code Playgroud)