C#中可以使用接口实现多重继承吗?
我经常在描述抽象类和接口的文章中遇到,C#不支持多重继承,但可以使用接口来实现。我不同意这一点,原因如下:
- 我们总是从任何类继承状态和行为。
- 接口不定义状态或行为。
- 我们不能从接口继承任何东西,但总是要实现它。
所以底线是C#不支持多重继承,接口不能帮助我们实现多重继承(事实上我们永远不能从接口继承)。
I often encounter in articles which describe abstract class and interface, that C# does not support multiple inheritance but can be achieved using interfaces. I don't agree to that for the following reasons
- We always inherit the state and behavior from any class.
- Interface does not define the state or behavior.
- We cannot inherit anything from an interface but always implement it.
So bottom line is that C# does not support multiple inheritance and interfaces cannot help us achieve multiple inheritance (in fact we can never inherit from an interface).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您不能在 C# 中实现多重继承。
但是,您可以通过接口获得多重继承的一些好处,即可以向类添加契约以使其适合系统的其他部分的部分,即替换原则。
但是不,您无法获得从多个基类继承行为的部分。
No, you can not implement multiple inheritance in C#, period.
You can, however, get some of the benefits of multiple inheritance through interfaces, namely the part where you can add contracts to a class to make it fit other parts of the system, the substitution principle.
But no, you can not get the part where you inherit behavior from multiple base classes.
Disputable 继承。从界面“继承”是一种查看界面的方式。它确实满足替代原则。
但我同意“实现”接口是更常见的表达/视图。
Disputable. "Inheriting" from an interface is a way of viewing it. It does satisfy the substitution principle.
But I agree that "Implementing" an interface is a more common expression/view.