Does C# support multiple inheritance?

2020-01-24 08:00发布

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 bunch on the net.

17条回答
闹够了就滚
2楼-- · 2020-01-24 08:27

You may want to take your argument a step further and talk about design patterns - and you can find out why he'd want to bother trying to inherit from multiple classes in c# if he even could

查看更多
啃猪蹄的小仙女
3楼-- · 2020-01-24 08:31

Multiple inheritance is not supported in C#.

But if you want to "inherit" behavior from two sources why not use the combination of:

  • Composition
  • Dependency Injection

There is a basic but important OOP principle that says: "Favor composition over inheritance".

You can create a class like this:

public class MySuperClass
{
    private IDependencyClass1 mDependency1;
    private IDependencyClass2 mDependency2;

    public MySuperClass(IDependencyClass1 dep1, IDependencyClass2 dep2)
    {
        mDependency1 = dep1;
        mDependency2 = dep2;
    }

    private void MySuperMethodThatDoesSomethingComplex()
    {
        string s = mDependency1.GetMessage();
        mDependency2.PrintMessage(s);
    }
}

As you can see the dependecies (actual implementations of the interfaces) are injected via the constructor. You class does not know how each class is implemented but it knows how to use them. Hence, a loose coupling between the classes involved here but the same power of usage.

Today's trends show that inheritance is kind of "out of fashion".

查看更多
够拽才男人
4楼-- · 2020-01-24 08:31

Actually, it depends on your definition of inheritance:

  • you can inherit implementation (members, i.e. data and behavior) from a single class, but
  • you can inherit interfaces from multiple, well, interfaces.

This is not what is usually meant by the term "inheritance", but it is also not entirely unreasonable to define it this way.

查看更多
何必那么认真
5楼-- · 2020-01-24 08:35

C# 3.5 or below does not support the multiple inheritance, but C# 4.0 could do this by using, as I remembered, Dynamics.

查看更多
放我归山
6楼-- · 2020-01-24 08:38

C# does not support multiple inheritance of classes, but you are permitted to inherit/implement any number of interfaces.

This is illegal (B, C, D & E are all classes)

class A : B, C, D, E
{
}

This is legal (IB, IC, ID & IE are all interfaces)

class A : IB, IC, ID, IE
{
}

This is legal (B is a class, IC, ID & IE are interfaces)

class A : B, IC, ID, IE
{
}

Composition over inheritance is a design pattern that seems to be favorable even in languages that support multiple inheritance.

查看更多
登录 后发表回答