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 t = typeof(Car);
System.Type genericType= generic.MakeGenericType(new System.Type[] { t});
Activator.CreateInstance(genericType, args);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19989 次 |
| 最近记录: |