How to simulate multiple inheritance without interfaces?

戏子无情 提交于 2019-12-12 14:13:21

问题


How can I simulate multiple inheritance in C# without using interfaces. I do believe, interfaces abilityes are not intended for this task. I'm looking for more 'design pattern' oriented way.


回答1:


ECMA-334, § 8.9 Interfaces
...
Interfaces can employ multiple inheritance.

So for as far C# (limited) support of 'multiple inheritance' goes, interfaces are the official way.




回答2:


Like Marcus said using interface + extension methods to make something like mixins is probably your best bet currently.

also see: Create Mixins with Interfaces and Extension Methods by Bill Wagner Example:

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");
            }

}

prints splasshy,splashy Not an easy Job




回答3:


Multiple inheritance in a form of a class is not possible, but they may be implemented in multi-level inheritance like:

public class Base {}

public class SomeInheritance : Base {}

public class SomeMoreInheritance : SomeInheritance {}

public class Inheriting3 : SomeModeInheritance {}

As you can see the last class inherits functionality of all three classes:

  • Base,
  • SomeInheritance and
  • SomeMoreInheritance

But this is just inheritance and doing it this way is not good design and just a workaround. Interfaces are of course the preferred way of multiple inherited implementation declaration (not inheritance, since there's no functionality).




回答4:


Although not quite multiple inheritance, you can get "sort of mixin functionality" by combining interfaces with extension methods.




回答5:


As C# only supports single inheritance, I believe you'll need to add more classes.

Are there specific reasons for not using interfaces? It's not clear from your description why interfaces are not suitable.



来源:https://stackoverflow.com/questions/3849097/how-to-simulate-multiple-inheritance-without-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!