在运行时指定泛型集合类型参数

tim*_*tim 25 c# generics casting runtime

我有:

class Car {..}
class Other{
  List<T> GetAll(){..}
}
Run Code Online (Sandbox Code Playgroud)

我想要做:

Type t = typeof(Car);
List<t> Cars = GetAll<t>();
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

我想从运行时使用反射发现的类型的数据库中返回一个泛型集合.

小智 26

Type generic = typeof(List<>);    
Type specific = generic.MakeGenericType(typeof(int));    
ConstructorInfo ci = specific.GetConstructor(Type.EmptyTypes);    
object o = ci.Invoke(new object[] { });
Run Code Online (Sandbox Code Playgroud)

  • 这不是什么大不了的事,但你可以用Type.EmptyTypes替换传入GetConstructor的空类型数组.只是一点清洁,就是这样. (4认同)

Nat*_*n W 8

你可以使用反射:

Type t = typeof(Car);
System.Type genericType= generic.MakeGenericType(new System.Type[] { t});
Activator.CreateInstance(genericType, args);
Run Code Online (Sandbox Code Playgroud)