2016-12-02 108 views
0

我有使用动态类型实例化自定义类的问题。 例子,我有下面的类:动态类型实例创建

public class myClass<T> 
{ 
    public myClass(String header); 
} 

如果我使用下面的代码,一切正常:

var myInstance = new myClass<int>("myHeader"); 

不过,我在一个位置,我没有定义的int类型做,所以我需要从一个泛型类型参数动态地转换它。我试过到目前为止:

1.

Type myType = typeof(int); 
    var myInstance = new myClass<myType>("myHeader"); 

2.

int myInt = 0; 
    Type myType = myInt.GetType(); 
    var myInstance = new myClass<myType>("myHeader"); 

在所有案例中,我得到以下错误:

The type or namespace name 'myType' could not be found (are you missing a using directive or an assembly reference?)

的原因我不能使用int直接是因为我在运行时加载了特定程序集中的类型,所以它们不会“in” t“。

+0

你能做出功能一般,只是做'新myClass的( “myHeader”);'? –

+0

感谢Quantic,这也帮助了我。 – m506

回答

0

为了在运行时创建generic列表,您的必须使用使用Reflection

int myInt = 0; 
Type myType = myInt.GetType(); 

// make a type of generic list, with the type in myType variable 
Type listType = typeof(List<>).MakeGenericType(myType); 

// init a new generic list 
IList list = (IList) Activator.CreateInstance(listType); 

更新1:

int myInt = 0; 
Type myType = myInt.GetType(); 
Type genericClass = typeof(MyClass<>); 
Type constructedClass = genericClass.MakeGenericType(myType); 
String MyParameter = "value"; 
dynamic MyInstance = Activator.CreateInstance(constructedClass, MyParameter); 
+0

感谢Ali,作为补充,下面的完整代码: int myInt = 0; 类型myType = myInt.GetType(); 类型genericClass = typeof(MyClass <>); 类型constructClass = genericClass.MakeGenericType(myType); String MyParameter =“value”; dynamic MyInstance = Activator.CreateInstance(constructedClass,MyParameter); Regards – m506

+0

@ m506不客气。不要忘记接受答案,如果你正在寻找。我更新了这篇文章,并将您的代码放在那里。 –