【问题标题】:Passing in type argument to a method to be used to designate a generic type将类型参数传递给用于指定泛型类型的方法
【发布时间】:2013-10-16 20:51:00
【问题描述】:

是否可以将泛型与类型参数混合使用?比如有没有办法写成这样的代码:

IList GetListOfListsOfTypes(Type[] types)
{
    IList<IList> listOfLists = new List<IList>();

    foreach (Type t in types)
    {
        listOfLists.Add(new List<t>());
    }

    return listOfLists.ToList();
}

很明显,编译器不喜欢这样,但是有什么方法可以实现吗?

【问题讨论】:

  • 你不能让它与编译器一起工作。但是你可以使用反射调用泛型构造函数。
  • 这不是重复的,因为它使用泛型类型,而链接只指定静态系统类型。

标签: c# generics


【解决方案1】:

要使用反射来做到这一点,您必须从开放类型构造封闭的泛型类型;然后用我们有反射的选项之一来构造它。 Activator.CreateInstance 非常适合:

IList GetListOfListsOfTypes(Type[] types)
{
    IList<IList> listOfLists = new List<IList>();

    foreach (Type t in types)
    {
        Type requestedTypeDefinition = typeof(List<>);
        Type genericType = requestedTypeDefinition.MakeGenericType(t);
        IList newList = (IList)Activator.CreateInstance(genericType);
        listOfLists.Add(newList);
    }

    return listOfLists;
}

请注意,您正在从此方法返回非泛型 ILists 列表,这是必要的,因为我们在编译时不知道类型,因此为了使用您的新泛型列表,您可能需要再次使用反射。考虑是否值得 - 当然,这取决于您的要求。

【讨论】:

  • +1 - 这很好,因为它实际上会在返回父列表后为子列表保留正确的类型。
猜你喜欢
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多