首页 > 解决方案 > 在不知道类型的情况下构造泛型类

问题描述

我想在不知道类型的情况下构造一个具有泛型参数的泛型类。

List<T> genericList = new List<T>();

public void AddGenericValue<T>(T t1, T t2)
{
    for (int i = 0; i < genericList.Count; i++)
    {
        if (genericList[i].t1 == t1)
        {
            genericList[i].t2 = t2;
            return;

        }
    }

    genericList.Add(new GenericClass(t1, t2));
}

public class GenericClass<T>
{
    T t1;
    T t2;

    public GenericClass(T t1, T t2)
    {
        this.t1 = t1;
        this.t2 = t2;
    }
}

现在我得到错误使用泛型类型'GenericClass'需要一种类型的参数。

标签: c#generics

解决方案


声明类型时需要指定泛型参数:

new GenericClass<T>(t1, t2)

原因是不能为类推断类型参数,只能为方法推断。您可以通过编写工厂来使用它:

static class GenericClassFactory
{
  public static GenericClass<T> Create(T t1, T t2)
  {
    return new GenericClass<T>(t1, t2);
  }
}

现在你可以:

var foo = GenericClassFactory.Create(1, 2);

并将T由编译器推导出来。

此外,列表应该是正确的类型:

var genericList = new List<GenericClass<T>>();

如果您需要将列表存储为成员变量,那么您需要将泛型类型提升到类级别而不是方法级别:

class Foo<T>
{
    private readonly List<GenericClass<T>> genericList = new List<GenericClass<T>>();

    public void AddGenericValue(T t1, T t2)
    {
        for (int i = 0; i < genericList.Count; i++)
        {
            if (genericList[i].t1 == t1)
            {
                genericList[i].t2 = t2;
                return;

            }
        }

        genericList.Add(new GenericClass<T>(t1, t2));
    }
}

推荐阅读