如何在没有接口的情况下模拟多重inheritance?

如何在不使用接口的情况下模拟C#中的多重inheritance。 我相信,接口能力不适用于此任务。 我正在寻找更多’设计模式’导向的方式。

ECMA-334,§8.9接口

接口可以使用多重inheritance。

因此,对于“多重inheritance”的C#(有限)支持,接口是官方方式。

就像Marcus说的那样使用界面+扩展方法制作类似mixins的东西可能是你目前最好的选择。

另请参阅: 使用Bill Wagner创建具有接口和扩展方法的Mixins示例:

using System; public interface ISwimmer{ } public interface IMammal{ } class Dolphin: ISwimmer, IMammal{ public static void Main(){ test(); } public static void test(){ var Cassie = new Dolphin(); Cassie.swim(); Cassie.giveLiveBirth(); } } public static class Swimmer{ public static void swim(this ISwimmer a){ Console.WriteLine("splashy,splashy"); } } public static class Mammal{ public static void giveLiveBirth(this IMammal a){ Console.WriteLine("Not an easy Job"); } } 

打印splasshy,splashy不是一件容易的事

不可能以类的forms进行多重inheritance,但它们可以在多级inheritance中实现,如:

 public class Base {} public class SomeInheritance : Base {} public class SomeMoreInheritance : SomeInheritance {} public class Inheriting3 : SomeModeInheritance {} 

如您所见,最后一个类inheritance了所有三个类的function:

  • Base
  • SomeInheritance
  • SomeMoreInheritance

但这只是inheritance,这样做不是好设计,只是一种解决方法。 接口当然是多重inheritance实现声明的首选方式(不是inheritance,因为没有function)。

虽然不是多重inheritance,但您可以通过将接口与扩展方法相结合来获得“一种混合function”。

由于C#仅支持单inheritance,我相信您需要添加更多类。

是否有不使用接口的具体原因? 从您的描述中不清楚为什么接口不合适。