代码之家  ›  专栏  ›  技术社区  ›  kofucii

如何模拟没有接口的多重继承?

  •  3
  • kofucii  · 技术社区  · 14 年前

    如何在不使用接口的情况下在C中模拟多重继承。我相信,接口的能力是不适合这个任务的。我在寻找更多的“设计模式”导向方式。

    5 回复  |  直到 14 年前
        1
  •  1
  •   Henk Holterman    14 年前

    ECMA-334,?8.9接口

    接口可以使用多个继承。

    因此,就“多重继承”的C(有限)支持而言,接口是正式的方式。

        2
  •  5
  •   Roman A. Taycher    14 年前

    就像马库斯说的,使用接口+扩展方法来制作类似mixin的东西可能是目前最好的选择。

    还可以看到: Create Mixins with Interfaces and Extension Methods by Bill Wagner 例子:

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

    印刷品 飞溅,飞溅 不是一件容易的工作

        3
  •  3
  •   Robert Koritnik    14 年前

    以类的形式进行多重继承是不可能的,但它们可以在多层继承中实现,例如:

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

    如您所见,最后一个类继承了所有三个类的功能:

    • Base ,
    • SomeInheritance
    • SomeMoreInheritance

    但这仅仅是继承,这样做并不是一个好的设计,只是一个变通方法。接口当然是多个继承实现声明的首选方式(不是继承,因为没有任何功能)。

        4
  •  1
  •   Marcus Riemer    14 年前

    虽然继承不太多,但是通过将接口与扩展方法结合,您可以获得“某种混合功能”。

        5
  •  0
  •   Waleed Eissa    14 年前

    由于C只支持单一继承,我相信您需要添加更多的类。

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