为什么C#不继承基类的构造函数

为什么C#不继承基类的构造函数

本文介绍了为什么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#不继承基类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:37