<分区>
默认情况下,C# 中的方法是非虚拟的。 This answer to another question解释这样做的好处:
Classes should be designed for inheritance to be able to take advantage of it. Having methods virtual by default means that every function in the class can be plugged out and replaced by another, which is not really a good thing.
甚至安德斯·海尔斯伯格 seems to give the same reason :
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. [...] You don't want users overriding and hooking at any arbitrary point in an API, because you cannot necessarily make those promises.
我同意这个推理:通常当我创建一个非私有(private)方法时,我只想创建可以从类外部的某个地方调用的代码。通常,不会考虑其他人如何覆盖此方法以及会产生什么影响。对于特殊情况,我可以使用 virtual
来表示确实以覆盖有意义的方式创建了代码。
但是,默认情况下类仍然是未密封的。 默认 假设我付出了额外的努力来确保继承一个类是有意义的。
在这方面,类与方法有什么不同吗?
编辑
我真的不知道如何改变搁置 - 基于意见的事情。我从不征求意见。也许我必须明确地说出来?
我不想要意见。
正确答案要么提供类与方法不同的示例,要么声明在此上下文中没有区别。