繁体   English   中英

将type参数传递给用于指定泛型类型的方法

[英]Passing in type argument to a method to be used to designate a generic type

是否可以将泛型与Type参数混合使用? 例如,有没有办法编写这样的代码:

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

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

    return listOfLists.ToList();
}

很明显,编译器不喜欢这个,但有没有办法实现这一点?

要使用反射执行此操作,必须从open类型构造闭合泛型类型; 然后用反射中的一个选项构造它。 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;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM