2016-12-03 48 views
0

所以,我有這樣的代碼:可以在泛型方法內調用子類構造函數嗎?

public class Fruit { 
    public Fruit() { 
     // base class constructor 
    }    
} 
public class Apple: Fruit { 
    public Fruit(): base() { 
      // child class constructor 
    } 

} 


T MakeNew<T>(T item) where T: Fruit, new() { 

    T tempNewClass = new T(); 
    return tempNewClass; 

} 

,然後在我的程序:

Apple apple = new Apple(); 
Apple anotherApple = MakeNew<Apple>(apple); 

爲什麼anotherApple是蘋果類的,但我的方法內創建過程中,只有基礎構造函數被調用,就好像它只被視爲基類一樣?

我猜測,那是因爲方法init行上的new()關鍵字。

有沒有辦法在泛型方法內創建子類並調用它的構造函數?

PS:請,我正在學習C#,並盡我所能從互聯網上獲得我需要的所有答案。自從4天以來,我一直在絆倒這個問題,並沒有在其他任何地方找到工作答案。但我可能錯了,也許我只是在問錯誤的問題?

回答

0

這eaven編譯?

public class Apple: Fruit { 
    public Fruit(): base() { 
     // child class constructor 
    } 
} 

它不應該是

public class Apple: Fruit { 
    public Apple(): base() { 
     // child class constructor 
    } 
} 

當我調試它Apple構造得到Fruit構造後稱爲它必須是。

另一種選擇是

T MakeNew<T>() where T : Fruit, new() 
{ 
    var instance Activator.CreateInstance<T>(); 
    //Do stuff with instance 
    return instance: 
} 

如果你還需要你的參數T item那麼你可以重新添加。

0

您可能只是注意到基類構造函數總是在子類之前調用​​。嘗試運行下面的代碼以觀察行爲:

static void Main(string[] args) 
    { 
     Console.WriteLine("new Apple()"); 
     Apple apple = new Apple(); 

     Console.WriteLine(); 

     Console.WriteLine("MakeNew<Apple>(apple)"); 
     Apple anotherApple = MakeNew<Apple>(apple); 
    } 

    static private T MakeNew<T>(T item) where T: Fruit, new() 
    { 
     return new T(); 
    } 
    public class Fruit 
    { 
     public Fruit() 
     { 
      Console.WriteLine("Fruit Constructor"); 
     } 
    } 

    public class Apple : Fruit 
    { 
     public Apple() : base() 
     { 
      Console.WriteLine("Apple Constructor"); 
     } 
    } 
} 
相關問題