2016-12-02 147 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不客氣。不要忘記接受答案,如果你正在尋找。我更新了這篇文章,並將您的代碼放在那裏。 –