所以,我有這樣的代碼:可以在泛型方法內調用子類構造函數嗎?
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天以來,我一直在絆倒這個問題,並沒有在其他任何地方找到工作答案。但我可能錯了,也許我只是在問錯誤的問題?