简体   繁体   中英

Implicitly call parent constructors

I have a set of classes where my base has a constructor that takes a configuration object and handles transferring the values to its properties.

abstract class A { public A(ObjType MyObj){} } 
abstract class B : A {}
class C : A {}
class D : B {}
class E : B {}

Is it possible to implicitly call a non-default base constructor from child classes or would I need to explicitly implement the signature up the chain to do it via constructors?

abstract class A { public A(ObjType MyObj){} } 
abstract class B : A { public A(ObjType MyObj) : base(MyObj){} }
class C : A { public A(ObjType MyObj) : base(MyObj){} }
class D : B { public A(ObjType MyObj) : base(MyObj){} }
class E : B { public A(ObjType MyObj) : base(MyObj){} }

If that is the case, is it better to just implement a method in the base then have my factory immediately call the method after creating the object?

Implicitly ? No, constructors are not inherited. Your class may explicitly call it's parent's constructor. But if you want your class to have the same constructor signatures as the parent class's, you must implement them.

For example:

public class A
{
    public A(int someNumber)
    {
    }
}

// This will not compile becase A doesn't have a default constructor and B 
// doesn't inherit A's constructors.
public class B : A
{
}

To make this work you'd have to explicitly declare the constructors you want B to have, and have them call A's constructors explicitly (unless A has a default constructor of course).

public class B : A
{
    public B(int someNumber) : base(someNumber)
    {
    }
}

不,不可能隐式调用非默认基本构造函数,而必须使其显式。

You need to explicitly implement it up the chain. Also, importantly, in your original code, you will not be able to call a new B() , since A does not have a default constructor, and B does not call A 's constructor that has an arg.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM