且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么默认情况下Java中的方法是虚拟的,而C#中默认是非虚拟的?

更新时间:2022-12-04 20:43:39

Anders Hejlsberg:(C#首席架构师)


有几个原因。一个是
的表现。我们可以观察到,当
的人用Java编写代码时,他们会忘记
来标记他们的方法。
因此,这些方法是虚拟的。
因为它们是虚拟的,所以它们也没有
表现。与
相关的虚拟方法只有
的性能开销。这是一个
问题。

There are several reasons. One is performance. We can observe that as people write code in Java, they forget to mark their methods final. Therefore, those methods are virtual. Because they're virtual, they don't perform as well. There's just performance overhead associated with being a virtual method. That's one issue.

更重要的问题是版本控制。
有两种关于
虚拟方法的思想流派。学院的b $ b b想法说:所有东西都应该是
虚拟,因为我可能希望有一天
覆盖它。务实的
思想,来自
构建真实应用程序,以现实世界
运行,说:我们必须真正小心我们制作的产品。
虚拟。

A more important issue is versioning. There are two schools of thought about virtual methods. The academic school of thought says, "Everything should be virtual, because I might want to override it someday." The pragmatic school of thought, which comes from building real applications that run in the real world, says, "We've got to be real careful about what we make virtual."

当我们在
平台上制作虚拟东西时,我们正在制作大量的
承诺它在
的未来发展。对于非虚方法,我们
承诺当你调用这个
方法时,x和y会发生。当我们
在API中发布虚拟方法时,我们
不仅承诺当你调用
这个方法时,x和y也会发生。我们
也承诺当你用这个方法覆盖
时,我们将在这个
特定序列中调用它来关于
这些其他的方法,状态将是
in这个和那个不变量。

When we make something virtual in a platform, we're making an awful lot of promises about how it evolves in the future. For a non-virtual method, we promise that when you call this method, x and y will happen. When we publish a virtual method in an API, we not only promise that when you call this method, x and y will happen. We also promise that when you override this method, we will call it in this particular sequence with regard to these other ones and the state will be in this and that invariant.

每当你在API中说虚拟时,
就会创建一个回调挂钩。作为
操作系统或API框架设计师,
你必须真正小心
。你不希望用户覆盖
并挂钩
中的任意一个API,因为你不一定能
做出这些承诺。人们可能没有完全理解他们在b $ b虚拟的东西时所做的承诺。

Every time you say virtual in an API, you are creating a call back hook. As an OS or API framework designer, you've got to be real careful about that. You don't want users overriding and hooking at any arbitrary point in an API, because you cannot necessarily make those promises. And people may not fully understand the promises they are making when they make something virtual.