[英]Call the base Constructor in the Constructor of the subclass
Is it possible to call the base Constructor at spicific point in the constructer of the subclass like: 是否可以在子类的构造函数的特定点调用基本构造函数,例如:
public class SuperClass
{
public SuperClass(Object myObject)
{
// init some values ...
}
}
public class SubClass: SuperClass
{
public SubClass(): base(Object myObject)
{
//Check some preconditions
base(myObject);
// Do some other stuff
}
}
No, it's not possible. 不,不可能。
One way to achieve this behavior you could extract the contents of the base constructor out into a method and then call that method from the subclass. 实现此行为的一种方法是,可以将基本构造函数的内容提取到方法中,然后从子类中调用该方法。
Another less closely tied method would be to just not use inheritance here. 另一个联系不紧密的方法是在这里不使用继承。 It's possible that this is a situation in which composition would make more sense.
在这种情况下,组合可能更有意义。 (It's impossible to say for sure without knowing more information though.)
(但是,如果不知道更多信息,就无法确定地说。)
No, because at //Check some preconditions
you'd have a partially constructed object. 不,因为在
//Check some preconditions
您将拥有部分构造的对象。 This would lead to all sorts of problems. 这将导致各种问题。
The right syntax is 正确的语法是
public class SubClass: SuperClass
{
public SubClass(object myObject): base(myObject)
{
}
}
Here is link of using constructors. 这是使用构造函数的链接 。 It is impossible to call it in ctor's body directly.
不能直接在ctor的体内称呼它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.