C# 中的多级继承构造函数
C#中有没有办法调用祖父的构造函数?假设我有:
public class A
{
public A(parameterX x)
{
doSomething();
}
}
public class B : A
{
public B(parameterX x) : base(x)
{
doSomethingElse();
}
}
然后我有:
public class C : B
{
}
我希望 C 中的构造函数调用 A 中的构造函数,我可以为此使用什么? 有没有类似的东西:
public C(parameterX x) : base : base(x)
或者我怎样才能从C调用A中的构造函数?
谢谢。
Is there a way in C# to call the grandfather's constructor? Let's say I have:
public class A
{
public A(parameterX x)
{
doSomething();
}
}
public class B : A
{
public B(parameterX x) : base(x)
{
doSomethingElse();
}
}
And then I have:
public class C : B
{
}
And I want the constructor in C to call the constructor in A, what can I use for this?
Is there something like:
public C(parameterX x) : base : base(x)
Or how can I just call the constructor in A from C?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能调用祖父类的构造函数。
但是,您也不需要这样做,因为基类已经这样做了。
当您编写
public C(parameterX x) : base(x)
时,它将调用B(x)
,而 B(x) 又会调用A(x)< /代码>。
一般来说,由于您的基类的构造函数将始终调用其基构造函数(您的祖父母),因此能够显式调用祖父母构造函数是没有意义的,因为这最终会构造它两次。
You cannot call a grandparent class' constructor.
However, you don't need to either, since the base class already does.
When you write
public C(parameterX x) : base(x)
, it will callB(x)
, which will in turn callA(x)
.In general, since your base class' constructor will always call its base constructor (your grandparent), it wouldn't make sense to be able to explicitly call the grandparent constructor, since that would end up constructing it twice.
虽然我不太明白您想要做什么,并且您可能可以提出更好的实际设计,但您可能可以通过在 B 中添加另一个将 Bar 参数作为 A 的构造函数来实现您所需要的,但是做其中没有任何内容只是简单地调用 A(Bar) 构造函数,这样当您执行 C(bar) : base(bar) 时,它将转到 B,然后转到 A。丑陋得要命。
Although I don't really understand what is that you are trying to do and you probably can come up with a better actual design, you can probably achieve what you need by adding another constructor in B that takes the Bar parameter as A, but do nothing in it simply calling A(Bar) constructor, that way when you do C(bar) : base(bar) it will go to B and then to A. Ugly as hell.