这绝对是主观的,但我想尽量避免它变成争论。我认为如果人们恰当地对待它,这将是一个有趣的问题。

这个问题的想法来自于我对“你最讨厌的语言的哪五件事?”问题的回答。我认为c#中的类在默认情况下应该是密封的——我不会把我的理由放在这个问题上,但我可能会写一个更完整的解释来回答这个问题。我对评论中的讨论热度感到惊讶(目前有25条评论)。

那么,你有什么有争议的观点?我宁愿避免那些基于相对较少的基础而导致相当宗教的事情(例如,大括号放置),但例如可能包括“单元测试实际上并没有多大帮助”或“公共字段确实是可以的”之类的事情。重要的是(至少对我来说)你的观点背后是有理由的。

请提出你的观点和理由——我鼓励人们投票给那些有充分论证和有趣的观点,不管你是否恰好同意这些观点。


当前回答

好吧,我说过我会更详细地阐述我的“密封类”观点。我想有一种方法可以展示我感兴趣的答案,那就是给我自己一个答案:)

意见:在c#中,默认情况下类应该是密封的

推理:

There's no doubt that inheritance is powerful. However, it has to be somewhat guided. If someone derives from a base class in a way which is completely unexpected, this can break the assumptions in the base implementation. Consider two methods in the base class, where one calls another - if these methods are both virtual, then that implementation detail has to be documented, otherwise someone could quite reasonably override the second method and expect a call to the first one to work. And of course, as soon as the implementation is documented, it can't be changed... so you lose flexibility.

C# took a step in the right direction (relative to Java) by making methods sealed by default. However, I believe a further step - making classes sealed by default - would have been even better. In particular, it's easy to override methods (or not explicitly seal existing virtual methods which you don't override) so that you end up with unexpected behaviour. This wouldn't actually stop you from doing anything you can currently do - it's just changing a default, not changing the available options. It would be a "safer" default though, just like the default access in C# is always "the most private visibility available at that point."

通过让人们明确表示他们希望人们能够从他们的类中派生,我们将鼓励他们更多地思考这个问题。这也可以帮助我解决我的懒惰问题——虽然我知道我应该密封几乎所有的类,但我很少真的记得这样做:(

对方观点:

我可以看到这样一种说法:可以相对安全地派生没有虚方法的类,而不需要额外的灵活性和通常需要的文档。目前我不确定如何应对这个问题,只能说我相信意外打开类的危害比意外密封类的危害更大。

其他回答

汇编语言是最好的编程语言。

这是我的:

“你不需要(文本)语法来表达对象及其行为。”

我赞同乔纳森·爱德华兹和他的潜台词项目——http://alarmingdevelopment.org/的观点

删除类。 . net Framework中隐式处理异常的类的数量(类的方法)。和一个哑巴共事是很困难的。

这个问题让我感到有趣的是,我刚刚读了答案的第一页,到目前为止,我还没有发现一个有争议的观点。

也许这更能说明stackoverflow产生共识的方式。也许我应该从最底层开始。: -)

(未命名)元组是邪恶的

如果您使用元组作为具有唯一含义的多个对象的容器,请改用类。 如果您使用它们来保存几个应该通过索引访问的对象,请使用列表。 如果您使用它们从一个方法中返回多个值,请使用Out参数(这需要您的语言支持引用传递) 如果这是代码混淆策略的一部分,那就继续使用它们!

我看到人们使用元组只是因为他们懒得给他们的对象命名。API的用户将被迫基于无意义的索引(而不是有用的名称)访问元组中的项。