【问题标题】:Creating an instance of a generic [duplicate]创建一个通用的实例[重复]
【发布时间】:2022-02-14 22:34:14
【问题描述】:

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

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

    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) 和大量其他变体,但很明显我只是不明白 Types和泛型工作。

任何帮助将不胜感激。

【问题讨论】:

  • 您需要添加以下通用约束where T : new() 。请参阅docs 了解不同的选项

标签: c# list unity3d generics types


【解决方案1】:

你已经离答案不远了。缺少的部分是将T 类型限制为只允许具有公共无参数构造函数的对象。

这是通过generic type-constraint wherenew-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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多