C#是否支持多继承4.0?

Edu*_*nis 2 c# inheritance

我最近参加了一次练习C#技能测试,其中一个问题是,

C#是否支持多重继承?

我回答是的,并且被标记为错误.经过一些在线研究后,它充满了为什么不支持它的答案:

C#中的多重继承支持

为什么Java或C#中不允许多重继承?

http://www.codeproject.com/Questions/652495/Why-does-csharp-doesnt-support-Multiple-inheritanc

然后我去尝试复制我尝试从已经从基类继承的类继承时应该得到的错误,并且没有错误.我正在使用控制台应用程序,我最近升级到.net 4.5,也许事情发生了变化?

我测试的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            Leo bk = new Leo();

            bk.avgWords();

            Console.ReadLine();

        }

        public void bubbleSort(int[] input)
        {

        }

        public void insertionSort(int[] input)
        {

        }
    }

    public class Gatsby : Books
    {


        public override void avgWords()
        {

            Console.WriteLine(5);

        }

    }

    public class Leo : Gatsby
    {


        public override void avgWords()
        {
            Console.WriteLine(7);
        }

    }

    public class Dicaprio : Leo
    {


    }

    public class Books
    {

        public int id { get; set; }
        public string title { get; set; }
        public string author { get; set; }

        public virtual void avgWords()
        {


            Console.WriteLine(3);
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 10

然后我去尝试复制我尝试从已经从基类继承的类继承时应该得到的错误,并且没有错误.我正在使用控制台应用程序,我最近升级到.net 4.5,也许事情发生了变化?

不,这仍然被认为是单一继承.您的类仅从单个基类继承.

某些语言(如C++)允许您从多个类继承.C#版本将是这样的:

class Foo {} 
class Bar {}

// This is invalid in C#!
class Baz : Foo, Bar {}
Run Code Online (Sandbox Code Playgroud)

但是,这是不允许的.

需要注意的是C#容许但是你实现多个接口.


nos*_*tio 5

C# 支持多重继承吗?

您不能从多个基类继承,但与 COM 一样,您可以通过多个接口以及包含和委托重用多个基类:

// class C1 implements interface I1
interface I1
{
    void M1();
}

class C1 : I1
{
    public void M1() { Console.WriteLine("C1.M1"); }
}

// class C2 implements interface I2
interface I2
{
    void M2();
}

class C2 : I2
{
    public void M2() { Console.WriteLine("C2.M2"); }
}

// class C reuses C1 and C2
// it implements I1 and I2 and delegates them accordingly
class C: I1, I2
{
    C1 c1;
    C2 c2;

    void I1.M1() { c1.M1(); }

    void I2.M2() { c2.M2(); }
}
Run Code Online (Sandbox Code Playgroud)