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条回答
【Aperson】
2楼-- · 2020-01-24 08:20

As an additional suggestion to what has been suggested, another clever way to provide functionality similar to multiple inheritance is implement multiple interfaces BUT then to provide extension methods on these interfaces. This is called mixins. It's not a real solution but it sometimes handles the issues that would prompt you to want to perform multiple inheritance.

查看更多
Lonely孤独者°
3楼-- · 2020-01-24 08:21

Like Java (which is what C# was indirectly derived from), C# does not support multiple inhertance.

Which is to say that class data (member variables and properties) can only be inherited from a single parent base class. Class behavior (member methods), on the other hand, can be inherited from multiple parent base interfaces.

Some experts, notably Bertrand Meyer (considered by some to be one of the fathers of object-oreiented programming), think that this disqualifies C# (and Java, and all the rest) from being a "true" object-oriented language.

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

Nope, use interfaces instead! ^.^

查看更多
劫难
5楼-- · 2020-01-24 08:24

You cannot do multiple inheritance in C# till 3.5. I dont know how it works out on 4.0 since I have not looked at it, but @tbischel has posted a link which I need to read.

C# allows you to do "multiple-implementations" via interfaces which is quite different to "multiple-inheritance"

So, you cannot do:

class A{}

class B{}

class C : A, B{}

But, you can do:

interface IA{}
interface IB{}

class C : IA, IB{}

HTH

查看更多
虎瘦雄心在
6楼-- · 2020-01-24 08:25

Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should be followed by class name in the signature.

interface A { }
interface B { }
class Base { }
class AnotherClass { }

Possible ways to inherit:

class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)

This is not legal:

class SomeClass : Base, AnotherClass { }
查看更多
聊天终结者
7楼-- · 2020-01-24 08:26

Simulated Multiple Inheritance Pattern
http://www.codeproject.com/KB/architecture/smip.aspx enter image description here

查看更多
登录 后发表回答