Why aren't classes sealed by default?

前端 未结 9 1738
天命终不由人
天命终不由人 2020-12-05 22:59

I was just wondering, since the sealed keyword\'s existence indicates that it\'s the class author\'s decision as to whether other classes are allowed to inh

相关标签:
9条回答
  • 2020-12-05 23:33

    I can't recall having heard a rationale for the decision to have classes not sealed by default. However, there are certainly quite a few people who believe that C# should have been spec'ed to have sealed be the default:

    http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx

    0 讨论(0)
  • 2020-12-05 23:34

    In my opinion there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more.

    If you want a class to be inheritable then you write

    public extensible class MyClass
    

    otherwise

    public sealed class MyClass
    

    BTW I think the same should go with access modifiers, disallow default access modifiers.

    0 讨论(0)
  • 2020-12-05 23:40

    I'd say it was just a mistake. I know many people (including myself) who believe that classes should indeed be sealed by default. There are at least a couple of people in the C# design team in that camp. The pendulum has swung somewhat away from inheritance since C# was first designed. (It has its place, of course, but I find myself using it relatively rarely.)

    For what it's worth, that's not the only mistake along the lines of being too close to Java: personally I'd rather Equals and GetHashCode weren't in object, and that you needed specific Monitor instances for locking too...

    0 讨论(0)
  • 2020-12-05 23:47

    I see two simple reasons:

    1. Inheritance is a foundational principle of OO, so disallowing it by default wouldn't be intuitive.
    2. The majority of classes are designed to allow inheritance, so allowing inheritance by default saves typing.
    0 讨论(0)
  • 2020-12-05 23:47

    sealed classes prevent inheritance and therefore are an OO abombination. see this rant for details ;-)

    0 讨论(0)
  • 2020-12-05 23:57

    You could probably make just as many arguments in favor of sealed-by-default as you could against it. If it were the other way around, someone would be posting the opposite question.

    0 讨论(0)
提交回复
热议问题