关于C#构造函数的几个问题
在C#中关于构造函数的继承:
- 我读到构造函数不能被继承。
- 如果基类包含一个或多个构造函数,派生类必须始终调用其中之一吗?派生类不可能跳过基类的构造函数吗?
- 派生类可以有自己的构造函数,但它必须调用基类构造函数之一。
这些说法正确吗?
In C# regarding the inheritance of constructors:
- I have read that constructors cannot be inherited.
- If the base class contains a constructor, one or more, the derived class have to always call one of them? It is not possible that the derived class can skip the constructor of the base class?
- Derived class can have its own constructor but it has to call one of the base class constructors.
Are these statements corrects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你是对的,构造函数不是继承的。因此,仅仅因为
Object
有一个无参数构造函数,并不意味着String
有一个无参数构造函数。来自 C# 4 规范第 1.6.7.1 节:<块引用>
与其他成员不同,实例构造函数不是继承的,并且类除了在类中实际声明的实例构造函数之外没有实例构造函数。如果没有为类提供实例构造函数,则会自动提供一个不带参数的空实例构造函数。
是的,派生类构造函数的构造函数链将始终通过其基类构造函数...尽管它可能是间接的,因为它可以通过
this(... 链接到同一类中的另一个构造函数。 )
而不是base(...)
。如果您未指定this(...)
或base(...)
,则相当于base()
- 调用基类中的无参数构造函数。有关详细信息,请参阅我的有关构造函数链的文章。
Yes, you're right, constructors are not inherited. So just because
Object
has a parameterless constructor, that doesn't mean thatString
has a parameterless constructor, for example. From section 1.6.7.1 of the C# 4 spec:Yes, the constructor chain of a derived class constructor will always go through its base class constructor... although it may be indirectly, as it could chain to another constructor in the same class via
this(...)
instead ofbase(...)
. If you don't specify eitherthis(...)
orbase(...)
, that's equivalent tobase()
- calling the parameterless constructor in the base class.See my article on constructor chaining for more information.
1.您不能继承构造函数,但您可以链接构造函数。示例:
2. 是的,例如,您无法实例化从具有所有私有构造函数的对象派生的类(除了 Jon 在下面的评论中提到的特定场景) 。您不能跳过基类的构造函数,但可以有多个重载,并选择您选择使用的构造函数。
3.是的,不确定这里的问题是什么。
1. You cannot inherit constructors, but you can chain constructors. Example:
2. Yes, for example, you cannot instantiate a class derived from an object with all private constructors (except in the particular scenario that Jon mentions below in his comment). You cannot skip the constructor of a base class, but you can have multiple overloads, and select the constructor you choose to use.
3. Yes, not sure what the question is here.
1 是
2 你不能跳过构造函数,但我认为你不能在默认构造函数中执行任何操作。就像
3 是的。看我之前的例子。
1 Yes
2 You cannot skip constructor but I think you could do nothing in default constructor. Just like
3 Yes. See my previous example.