2012-09-18 80 views
4

我試圖找到具有特定簽名的構造函數。此構造函數在當前類型中不存在,但它在其父類中存在。爲了說明:C#GetConstructor()不返回父構造函數

public class Base 
{ 
    public Base() 
    { 

    } 

    public Base(string a1, string a2, string a3) 
    { 
     ... 
    } 
} 

public class Child : Base 
{ 

} 

的問題是,我似乎無法找到.ctor與字符串參數與.GetConstructor,甚至還試圖如:

typeof(Child).GetConstructor(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(string), typeof(string) }, null); 

typeof(Child)typeof(Base),自然,作品。

有沒有什麼我找不到關於尋找父構造函數?

回答

3

構造函數不是繼承的,所以即使使用FlattenHierarchy也無法通過子元素找到它們。

你必須通過兒童循環找到它。

1

Child類根本沒有你正在尋找的構造函數。你不能寫:

Child c = new Child("a", "b", "c"); 

所以這是毫無意義的尋找,不能用於實例給定類型的構造函數。

所有的兒童類有是默認的構造函數:

Child c = new Child(); 

如果除去從Base類的默認構造函數,則Child類將有您正在尋找的構造。

+0

從「Base」中刪除默認構造函數不會給Child提供三個參數構造函數。起初我以爲這是一件非常整潔的東西,我從來不知道,但我在.NET 4中試過,並且不,仍然得到「'Child'不包含帶3個參數的構造函數」 –

0

嘗試調用

var child = new Child("1", "2", "3") 

,你就會明白爲什麼構造上不可Child