2012-09-04 85 views
0

讓一些麻煩說我有這樣的例子:與子類的構造

class A : SomeAbstractClassWithProperties 
{ 
    public A(string id, int size) 
    { 
    this.Name = "Name1"; 
    this.Something = new SomethingElse(id, size); 
    } 

    //...some stuff 
} 

class B : A 
{ 
    public B(string id, int size) 
    { 
    this.Name = "Name2"; 
    this.Something = new SomethingElse(id, size); 
    } 
} 

確定這是不是要去工作:

Inconsistent accessibility: base class A is less accessible than class 'B' 
'A' does not contain a constructor that takes 0 arguments 

但是我們看到的A類類的構造函數B幾乎相同。只是this.Name是不同的。我怎麼能重寫B類?有什麼建議麼?謝謝

+0

這是一個有點娛樂,每個人都已經張貼着複製無效的構造函數聲明'公共類B(字符串ID,INT大小){/ *東西* /}'答案:) –

回答

3

請更新您的代碼

class B : A 
{ 
    public class B(string id, int size) : base(id, size) 
    { 
    this.Name = "Name2"; 
    } 
} 

的情況是你B的構造函數試圖調用該desn't存在A()默認構造函數。

0

您應該添加默認的(不帶參數)構造函數A類或修改B類的構造函數這樣

public class B(string id, int size) : base(id, size) 
    { 
    this.Name = "Name2"; 
    this.Something = new SomethingElse(id, size); 
    } 
+1

我真的需要添加此。 Something = new SomethingElse(id,size);再次? – silla

0

當您創建B的情況下,由於B從A伸出你會有這麼稱呼A的構造函數。 由於您正在爲類A定義一個構造函數,因此不再具有缺省的無參數構造函數,因此您必須在B構造函數中調用A的構造函數來傳遞所需的參數。

public A(string id,int size):base(param1,param2...paramX)