C#不从基类继承构造函数 [英] C# does not inherit the constructor from base class

查看:219
本文介绍了C#不从基类继承构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

构造函数和继承

为什么构造函数不被继承?

当定义继承自基类的类时,我必须重新定义其所有构造函数。
我想知道为什么C#不支持从基类的构造函数继承?

When define class inherited from base class, I have to redefine all its constructors. I am wondering why C# does not support inherit from base class's constructors?

推荐答案

构造函数不是继承的,因为我们不会无法正确确定派生类对象的实例化方式。当所有派生类都隐式使用父类的构造函数时,在我看来这将是一个问题,因为如果我们忘记重新定义构造函数,那么该对象可能已被错误地初始化。如果您希望派生类构造函数与父类构造函数执行相同操作,请使用 base

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.

另外请注意,如果你没有自动运行基类构造函数(无参数)不要显式地调用任何其他基类构造函数来获取参数。所以调用 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#不从基类继承构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆