【发布时间】:2009-02-05 00:05:29
【问题描述】:
我有:
class Car {..}
class Other{
List<T> GetAll(){..}
}
我想做:
Type t = typeof(Car);
List<t> Cars = GetAll<t>();
我该怎么做?
我想从数据库中返回一个泛型集合,该集合是我在运行时使用反射发现的。
【问题讨论】:
标签: c# generics casting runtime
我有:
class Car {..}
class Other{
List<T> GetAll(){..}
}
我想做:
Type t = typeof(Car);
List<t> Cars = GetAll<t>();
我该怎么做?
我想从数据库中返回一个泛型集合,该集合是我在运行时使用反射发现的。
【问题讨论】:
标签: c# generics casting runtime
Type generic = typeof(List<>);
Type specific = generic.MakeGenericType(typeof(int));
ConstructorInfo ci = specific.GetConstructor(Type.EmptyTypes);
object o = ci.Invoke(new object[] { });
【讨论】:
您可以为此使用反射:
Type t = typeof(Car);
System.Type genericType= generic.MakeGenericType(new System.Type[] { t});
Activator.CreateInstance(genericType, args);
【讨论】: