在 C# 中使用接口如何克服多重继承问题?
据我了解,C# 不支持多重继承,解决方案是使用接口。但我不明白的是,为什么接口不会像多重继承那样产生钻石问题。使用接口如何避免多重继承的陷阱?
I understand that C# does not support multiple inheritance, and that the solution is to use interfaces instead. But what I don't understand is why interfaces doesn't create the diamond problem the same way as multiple inheritance would. How does using interfaces avoid the pitfalls of multiple inheritance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
一个类可以实现任意数量的接口,即使这些接口也扩展了其他接口。多重继承仅适用于类。
类存在钻石问题,因为存在实现冲突的可能性(如果
A
和B
具有相同的方法,并且C
都扩展了两者,这采取什么方法?)。另一方面,接口只需要一个实现类型来拥有它们声明的方法。如果在两个接口中定义了完全相同的方法,并且一个类实现了这两个接口,那么这并不重要。该类所需要做的就是提供该方法的实现,以便可以编写代码来调用该方法。这意味着,这是有效的:
请注意,一个类仍然可以从另一个类继承,加上任意数量的接口:
One class may implement any number of interfaces, even if those interfaces extend other interfaces as well. Multiple inheritance is not possible only with classes.
The diamond problem exists with classes because there is a possibility of clashing implementations (if
A
andB
have the same method andC
extends both, which method does it take?). Interfaces, on the other hand, simply require an implementing type to have the methods that they declare.If the exact same method is defined in two interfaces, and a class implements both interfaces, that doesn't matter. All the class needs to do is provide an implementation for the method so that code can be written to call that method. Meaning, this works:
Note that a class may still inherit from one other class, plus any number of interfaces:
仅使用接口时不存在“钻石问题”,因为不存在可能的模糊实现。阅读维基百科文章,其中包含完整的解释。
The "diamond problem" is not present when just using interfaces because there is no ambiguous implementation possible. Read the Wikipedia article, which contains a full explanation.
多个接口不会产生菱形问题,因为每个类必须提供自己的唯一实现,这意味着不存在资源共享。
C# 不允许多重继承,因为它们关心你,并让该语言尽可能防止搬起石头砸自己的脚。
Multiple interfaces will not create the diamond problem because each class must provide their own unique implementation, which means there is no sharing of resources.
C# does not allow multiple inheritance because they care about you, and made the language as shoot-yourself-in-the-foot-proof as possible.
我认为仅在 C# 范围内考虑这个问题是不公平的。
CLR
本身不支持多重继承。可能是因为他们想要支持目前不支持或将来不能支持的其他语言。I think it is not fair to think about this in scope of
C#
only.CLR
itself does not support multiple inheritance. May be because they wanted to support other languages that do not support it currently or cannot support it in future.如果你问继承:类只能继承一个类,但可以实现任意数量的接口。请参阅这篇有关 C# 中的继承和多态性的文章。
If you ask about inheritance: class can inherit only one class, but can implement any number of interfaces. See this article about inheritance and polymorphism in C#.
这是尝试实现通常可以通过多重继承实现的目标的一种可能方法。
This is a possible way to try to achieve something that you usually can achieve with multiple inheritance.
一次只能继承一个类和任意数量的接口
You can inherit only one class and any number of interfaces at a time