2013-03-23 73 views
-1

好,所以這個問題已經解決了,但所有的解決方案真的只能在簡單的程序中工作,我希望找到一個更有效的方法來做到這一點。所以讓我們假設我有這樣的代碼孩子的構造函數

public class Parent 
{ 
    int one; 
    int two; 
    public Parent(int A, int B) 
    { 
     one = A; 
     two = B; 
    } 
} 
public class Child : Parent 
{ 
    int three; 
    int four; 
    public Child(int C, int D) 
    { 
     three = C; 
     four = D; 
    } 
} 

確定這樣的孩子有所有的家長變量以及所有新的變量(它詮釋一個和兩個,以及三,四)。當我創建一個子對象

Child myChild = new Child(3,4); 

我只能夠把在孩子的構造規定的兩個值,我真的需要設置所有四個變量值(這兩個從父和兩名兒童)。這個唯一的解決辦法,我發現是沿

public class Child : Parent 
{ 
    int three; 
    int four; 
    public Child(int A, int B, int C, int D) : base(A, B) 
    { 
     three = C; 
     four = D; 
    } 
} 

但我負責的幾十個孩子的類和大約30父變量,因此上面的解決方案變得非常大線的東西和做家長的任何變化必須在每個子類中手動更改變量。是否有一種簡單的方法讓父母的構造函數接近兒童構造函數或者比上面提出的更高效的其他解決方案?

+2

你是什麼意思「幾十個孩子班級和大約30個父變量」?你似乎不瞭解繼承是如何工作的。 – wRAR 2013-03-23 11:01:53

+1

當你到達這一點時,你應該考慮修改你的班級結構。 – briantyler 2013-03-23 11:02:01

+0

將像'int three;'這樣的字段更改爲像這樣的屬性:'int three {get;保護組; }'。然後你可以將min設置爲子構造函數。 – 2013-03-23 11:05:01

回答

0

製作等領域的公共,去除構造函數,定義任何成員的數量,申報喜歡你的課:

public class Parent { 
    public int one; 
    public int two; 
} 

public class Child: Parent { 
    public int three; 
    public int four; 
} 

和實例它像

var child= 
    new Child { 
     one=1, 
     two=2, 
     three=3, 
     four=4 
    }; 
+0

我沒有看到任何改進。 – wRAR 2013-03-23 11:24:03

+0

@wRAR:改進? – 2013-03-23 11:25:34

+0

與原始代碼相比的改進。 – wRAR 2013-03-23 11:33:56

相關問題