2010-05-04 39 views
0
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 
} 

我的問題是我需要在類B中初始化列表a和b。如果我把它們放在構造函數1中,我怎樣才能在構造函數2中調用構造函數1?我不想重寫constructor2中的初始化語句。謝謝!如何同時調用當前類和父類的構造函數?

+0

爲什麼不創建一個方法來初始化'List'並從兩個構造函數中調用它們? – 2010-05-04 02:16:20

+1

委託給方法不允許初始化'只讀'成員,但我想齊格弗裏德並沒有表示他希望他們只讀。 – 2010-05-04 02:17:30

+0

是的,我剛剛嘗試過。所以從理論上講,不可能從當前類和父類中調用構造函數? – zsong 2010-05-04 02:17:45

回答

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 
    } 
} 
1

把它們放在構造函數2中並讓構造函數1調用構造函數2?或者將它們初始化爲內聯而不是在構造函數中?有很多方法來剝皮這隻貓。

1

如果您的初始化活動必須在多個構造函數中發生,請將它們放入單獨的私有方法中,然後從任何需要這些活動的構造函數中調用該方法。我不明白父母的構造函數與它有什麼關係,或者你爲什麼想從另一個構造函數中調用一個構造函數。

+0

我剛剛修改了我的問題,實際上在A類中還有另一個初始化。 – zsong 2010-05-04 02:20:02