如何同时调用当前类和父类的构造函数?

zs2*_*020 0 c#

public class A{
    List m;
    public A(int a, int b) {m=new List(); ...}
}


public class B : A{
    List a;
    List b;
    public B(){...}  //constructor1
    public B(int a, int b) : base(a,b){...} //constructor2
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我需要初始化类B中的列表a和b.如果我将它们放在构造函数1中,我怎样才能在构造函数2中调用构造函数1?我不想再次在构造函数2中重写初始化语句.谢谢!

Dan*_*Tao 5

听起来,你只是在心理上向后倾斜.我想你想要做的是:

public class B : A {
    List _a;
    List _b;

    public B(int a, int b) : base(a, b) {
        // this calls the base constructor

        // presumably you're initializing _a and _b in here?
        _a = new List();
        _b = new List();
    }

    // let x and y be your defaults for a and b
    public B() : this(x, y) {
        // this calls the this(a, b) constructor,
        // which in turn calls the base constructor
    }
}
Run Code Online (Sandbox Code Playgroud)