gpt4 book ai didi

c# - 为什么 Java 或 C# 中不允许多重继承?

转载 作者:IT老高 更新时间:2023-10-28 11:22:20 26 4
gpt4 key购买 nike

我知道在 Java 和 C# 中不允许多重继承。很多书只是说,不允许多重继承。但它可以通过使用接口(interface)来实现。没有讨论为什么不允许这样做。谁能准确告诉我为什么不允许这样做?

最佳答案

简短的回答是:因为语言设计者决定不这样做。

基本上,.NET 和 Java 设计者似乎都不允许多重继承,因为他们认为添加 MI增加了语言的复杂性,而提供的好处太少强>。

为了获得更有趣和更深入的阅读,网络上提供了一些文章,其中包含对一些语言设计者的采访。例如,对于 .NET,Chris Brumme(曾在 MS 从事 CLR 工作)解释了他们决定不这样做的原因:

  1. Different languages actually have different expectations for how MI works. For example, how conflicts are resolved and whether duplicate bases are merged or redundant. Before we can implement MI in the CLR, we have to do a survey of all the languages, figure out the common concepts, and decide how to express them in a language-neutral manner. We would also have to decide whether MI belongs in the CLS and what this would mean for languages that don't want this concept (presumably VB.NET, for example). Of course, that's the business we are in as a common language runtime, but we haven't got around to doing it for MI yet.

  2. The number of places where MI is truly appropriate is actually quite small. In many cases, multiple interface inheritance can get the job done instead. In other cases, you may be able to use encapsulation and delegation. If we were to add a slightly different construct, like mixins, would that actually be more powerful?

  3. Multiple implementation inheritance injects a lot of complexity into the implementation. This complexity impacts casting, layout, dispatch, field access, serialization, identity comparisons, verifiability, reflection, generics, and probably lots of other places.

You can read the full article here.

对于 Java,您可以阅读 this article :

The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple).

In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache.

关于c# - 为什么 Java 或 C# 中不允许多重继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/995255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com