来自运行时类型的泛型类 [英] Generics class from a runtime type
本文介绍了来自运行时类型的泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好
我有一个在运行时构建的类(RClass)并且还有一个Generic类DataLoader,如何创建一种DataLoader< RClass>并使用其方法
Hi guys
i have a class that build in runtime(RClass) and also have a Generic class DataLoader, how can i create a type of DataLoader<RClass> and use its methods
public interface IDataLoader<GType>
{
//some code
GType SampleMethod();
}
public class DataLoader <GType>: IDataLoader<GType>
{
GType SampleMethod(){
//some code
}
}
//class "RClass" created in runtime
MyClassBuilder MCB=new MyClassBuilder("RClass");
var myclass = MCB.CreateObject(new string[3] { "id", "name", "link" }, new Type[3] { typeof(int), typeof(string), typeof(string) });
Type myclassType = myclass.GetType();
var dta = typeof(DataLoader<>).MakeGenericType(myclassType);
// ?????
var gs = (???)Activator.CreateInstance(dta);
gs.SampleMethod();
推荐答案
我想你想要使用的是:
I think what you want to use would be something like:
Type BTP = typeof(B).MakeGenericType(TP);
System.Reflection.ConstructorInfo ctorBTP = BTP.GetConstructor(Type.EmptyTypes);
dynamic a = ctorBTP.Invoke(null);
我无法想象在编译时将其强类型化为 B< TP>
,因为该类型不在编译时存在。
这篇关于来自运行时类型的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文