可以通过Type实例动态设置泛型类的类型参数吗?

Eri*_*tas 0 .net c# generics

我想做类似下面的代码.

    public IList SomeMethod(Type t)
    { 
        List<t> list = new List<t>;
        return list;
    }
Run Code Online (Sandbox Code Playgroud)

当然,这不起作用.是否有其他方法可以使用对Type实例的引用动态设置泛型类的类型参数?

小智 7

试试这个:

public IList SomeMethod(Type t)
{ 
    Type listType = typeof(List<>);
    listType = listType.MakeGenericType(new Type[] { t});
    return (IList)Activator.CreateInstance(listType);
}
Run Code Online (Sandbox Code Playgroud)

  • 你也可以把它归结为一个单行:`return(IList)Activator.CreateInstnace((typeof(List <>)).MakeGenericType(t));` (2认同)