C#create Object obj = new T()?
我有一个超类,我们可以调用class A
和几个子类,例如class a1 : A
, class a2 : A
,…和a6 : A
。 在我的class B
,我有一组方法可以创建一个子类并将其添加到B
的List
中。
我想缩短我目前的代码。 所以不要写作
Adda1() { aList.Add( new a1() ); } Adda2() { aList.Add( new a2() ); } ... Adda6() { aList.Add( new a6() ); }
相反,我想写一些与此相似的东西
Add() { aList.Add( new T() ); // This gives an error saying there is no class T. }
那可能吗?
是否也可以约束T
必须是A
类型或其子类之一?