Why are constructors not inherited in C#?

后端 未结 5 2109
耶瑟儿~
耶瑟儿~ 2020-11-29 07:52

I\'m guessing there\'s something really basic about C# inheritance that I don\'t understand. Would someone please enlighten me?

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 08:43

    If you think about what would happen if constructors were inherited, you should start to see the problem.

    As nearly every type in .NET inherits from Object (which has a parameterless constructor), that means almost every type that you create would be forced to have a parameterless constructor. But there are many types where a parameterless constructor doesn't make sense.

    There would also be a problem with versioning. If a new version of your base type appears with a new constructor, you would automatically get a new constructor in your derived type. This would be a bad thing, and a specific instance of the fragile base class problem.

    There's also a more philosophical argument. Inheritance is about type responsibilities (this is what I do). Constructors are about type collaboration (this is what I need). So inheriting constructors would be mixing type responsibility with type collaboration, whereas those two concepts should really remain separate.

提交回复
热议问题