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

25

我有:

class Car {..}
class Other{
  List<T> GetAll(){..}
}

我想要做的事情:

Type t = typeof(Car);
List<t> Cars = GetAll<t>();

我该如何做到这一点?

我想从数据库返回一个通用集合,其类型是我在运行时使用反射发现的。

2个回答

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

4
这并不是什么大事,但你可以用 Type.EmptyTypes 替换传入 GetConstructor 的空类型数组。这样会更加简洁。 - Kilhoffer

8
您可以使用反射来实现此操作:
Type t = typeof(Car);
System.Type genericType= generic.MakeGenericType(new System.Type[] { t});
Activator.CreateInstance(genericType, args);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接