在 C# 中关于构造函数的继承:
- 我读到构造函数不能被继承。
- 如果基类包含一个构造函数,一个或多个,派生类必须总是调用其中之一?派生类总不能跳过基类的构造函数吧?
- 派生类可以有自己的构造函数,但它必须调用基类构造函数之一。
这些说法正确吗?
最佳答案
是的,你是对的,构造函数不是继承的。例如,仅仅因为
Object
有一个无参数构造函数,并不意味着String
有一个无参数构造函数。来自 C# 4 规范的第 1.6.7.1 节:Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided.
是的,派生类构造函数的构造函数链将始终通过其基类构造函数...尽管它可能是间接的,因为它可以通过
this( ...)
而不是base(...)
。如果您不指定this(...)
或base(...)
,则等同于base()
- 调用基类中的无参数构造函数。
查看我的 article on constructor chaining获取更多信息。
关于c# - 关于C#中构造函数的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5535501/