Does C# support multiple inheritance?

后端 未结 17 737
傲寒
傲寒 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:08

    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".

提交回复
热议问题