我有一個超類,我們可以調用class A
和幾個子類,例如class a1 : A
,class a2 : A
,...和a6 : A
。在我的class B
中,我有一組方法創建B
中的List<A>
並將其中的一個子類添加到List<A>
中。C#創建對象obj = new T()?
我想縮短我目前的代碼。因此,而不是寫
Adda1()
{
aList.Add(new a1());
}
Adda2()
{
aList.Add(new a2());
}
...
Adda6()
{
aList.Add(new a6());
}
相反,我想寫類似這樣
Add<T>()
{
aList.Add(new T()); // This gives an error saying there is no class T.
}
東西這可能嗎?
是否也可以約束T
必須是A
或其子類之一?
的可能重複[創建泛型類型的實例嗎?](http://stackoverflow.com/questions/731452/create-instance-通用類型) –