问题描述
在定义类从基类继承,我必须重新定义它的所有构造函数。我想知道从基类的构造函数,为什么C#能源部鼻涕支持继承?
解决方案在定义类从基类继承,我必须重新定义它的所有构造函数。我想知道从基类的构造函数,为什么C#能源部鼻涕支持继承?
解决方案构造函数不能被继承,因为我们不能够正确地确定我们的派生类对象实例化了
另外要注意的是,基类构造函数(无参数)会自动运行,如果你不显式调用任何其它基类构造函数接受参数。因此调用基()是多余的
。
When define class inherited from base class, I have to redefine all its constructors. I am wondering why c# doe snot support inherit from base class's constructors?
Constructors are not inherited because we wouldn't be able to properly determine how our derived class objects were instantiated. When all derived classes would use parent's constructors implicitly, in my oppinion it would be a problem because if we forgot to redefine constructor, the object might have been initialized incorrectly. If you would like the derived class constructor to do the same as parent class constructor, call it using base.
Also be aware of the fact that the base class constructor (parameterless) is automatically run if you don't call any other base class constructor taking arguments explicitly. So calling base() is redundant
.
这篇关于为什么C#不继承基类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!