C # create Object obj = new T ()?
Mam superklasę, do której możemy zadzwonićclass A
i kilka podklas, np.class a1 : A
, class a2 : A
, ... ia6 : A
. W moimclass B
, Mam zestaw metod, które tworzą i dodają jedną z podklas do aList<A>
wB
.
Chcę w tym momencie skrócić mój kod. Więc zamiast pisać
Adda1()
{
aList.Add( new a1() );
}
Adda2()
{
aList.Add( new a2() );
}
...
Adda6()
{
aList.Add( new a6() );
}
Zamiast tego chcę napisać coś podobnego do tego
Add<T>()
{
aList.Add( new T() ); // This gives an error saying there is no class T.
}
Czy to jest możliwe?
Czy można to również ograniczyćT
musi być typuA
lub jedną z jego podklas?