Does C# support multiple inheritance?

后端 未结 17 754
傲寒
傲寒 2020-11-27 05:34

A colleague and I are having a bit of an argument over multiple inheritance. I\'m saying it\'s not supported and he\'s saying it is. So, I thought that I\'d ask the brainy

17条回答
  •  庸人自扰
    2020-11-27 06:17

    You can't inherit multiple classes at a time. But there is an options to do that by the help of interface. See below code

    interface IA
    {
        void PrintIA();
    }
    
    class  A:IA
    {
        public void PrintIA()
        {
            Console.WriteLine("PrintA method in Base Class A");
        }
    }
    
    interface IB
    {
        void PrintIB();
    }
    
    class B : IB
    {
        public void PrintIB()
        {
            Console.WriteLine("PrintB method in Base Class B");
        }
    }
    
    public class AB: IA, IB
    {
        A a = new A();
        B b = new B();
    
        public void PrintIA()
        {
           a.PrintIA();
        }
    
        public void PrintIB()
        {
            b.PrintIB();
        }
    }
    

    you can call them as below

    AB ab = new AB();
    ab.PrintIA();
    ab.PrintIB();
    

提交回复
热议问题