创建泛型实例

Creating an instance of a generic

这可能是一个菜鸟问题,对于我的经验不足,请提前致歉...

所以我有一个包含数千个经常波动的元素的列表,所以我创建了这个 Coroutine 来更新它,而不是创建一个全新的列表并在每次更改时填充它...

    public static IEnumerator ListSetup(List<Vector3> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new Vector3());
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }

...而且效果很好。

然后,我想修改它以便它可以接受任何类型的列表,而不仅仅是 Vector3 的列表,但我在语法方面遇到了一些麻烦..

    public static IEnumerator ListSetup<T>(List<T> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new T());//Error Here
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }

我试过 typeof(T)、GetType(T)、typeof(T).MakeGenericType()、Add(T) 和大量其他变体,但很明显我就是不明白类型和泛型如何工作。

如有任何帮助,我们将不胜感激。

你已经离答案不远了。缺少的部分是将类型 T 限制为仅允许具有 public parameter-less 构造函数的对象。

这是通过 generic type-constraint where and the new-constraint

完成的
public static IEnumerator ListSetup<T> (List<T> list, int resolution) where T : new()
{
    while (list.Count != resolution)
    {
        if (list.Count < resolution)
            list.Add(new T());
        if (list.Count > resolution)
            list.RemoveAt(list.Count - 1);
    }
    yield return null;
}