How can I add a generic Type to my list? I tried to create an object of T but this doesn't work neither.
class Bar<T> where T : IDrink
{
List<T> storage = new List<T>();
public void CreateDrink()
{
storage.Add(T); //<- This doesn't work
}
}
T
is a type not an instance of that type. So you need a parameter in CreateDrink
or use a factory method that returns a new instance of T
.
If you want to create an instance the generic constraint must include new()
class Bar<T> where T : IDrink, new()
{
List<T> storage = new List<T>();
public void CreateDrink()
{
storage.Add(new T());
}
}
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
你可以这样做:
storage.Add(Activator.CreateInstance<T>());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.