C# 泛型 Class<T>

C# Generic Class<T>

如何将通用类型添加到我的列表中? 我试图创建一个 T 的对象,但这也不起作用。

class Bar<T> where T : IDrink
{
    List<T> storage = new List<T>();

    public void CreateDrink()
    {
        storage.Add(T); //<- This doesn't work
    }
}

你可以这样做:

storage.Add(Activator.CreateInstance<T>()); 

T 是一种类型,不是该类型的实例。因此,您需要 CreateDrink 中的参数或使用 returns T.

的新实例的工厂方法

如果要创建实例,通用约束必须包含 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.