如何在基类中声明构造函数,以便子类无需声明也可以使用它们?
我希望子类使用其父类的构造函数。但似乎我总是需要在子类中再次定义它们才能工作,如下所示:
public SubClass(int x, int y) : base (x, y) {
//no code here
}
所以我想知道我是否没有在父类中正确声明构造函数,或者是否没有直接的构造函数继承全部?
I want a subclass to use its parent's constructors. But it seems I always need to define them again in the subclass in order for that to work, like so:
public SubClass(int x, int y) : base (x, y) {
//no code here
}
So I'm wondering if I'm not declaring the constructor properly in the parent class, or is there no direct constructor inheritance at all?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你没有做错任何事。
在 C# 中,实例构造函数不会被继承,因此在继承类型上声明它们并链接到基本构造函数是正确的方法。
根据规范§1.6.7.1:
You are not doing anything wrong.
In C#, instance constructors do not get inherited, so declaring them on the inheriting type and chaining to the base constructor is the right way about it.
From the spec §1.6.7.1:
我知道这并不能直接回答你的问题;但是,如果大多数构造函数只是在前一个构造函数上引入一个新参数,那么您可以利用可选参数(在 C# 4 中引入)来减少需要定义的构造函数的数量。
例如:
上面的内容可以简化为:
并且它仍然允许您使用任意数量的参数初始化
BaseClass
和DerivedClass
:I know this doesn’t directly answer your question; however, if most of your constructors simply introduce a new parameter on the previous constructor, then you could take advantage of optional arguments (introduced in C# 4) to reduce the number of constructors you need to define.
For example:
The above can be reduced to:
And it would still allow you to initialize both
BaseClass
andDerivedClass
with any number of arguments:构造函数不是从基类继承到派生类的。每个构造函数必须首先调用基类 ctor。编译器只知道如何调用无参数构造函数。如果基类中没有这样的ctor,则必须手动调用它。
Constructors aren't inherited from base class to derived. Each constructor must call base class ctor first. Compiler knows only how to call parameterless ctor. If there is not such ctor in base class, you have to call it manually.
如果基类没有默认构造函数,则必须在子类中重新声明它。这就是 OOP 在 .NET 中的工作方式。
If the base class doesn't have a default constructor you must redeclare it in the child class. That's how OOP work in .NET.