2008-09-24 45 views
3

假設我只有泛型類名作爲「MyCustomGenericCollection(MyCustomObjectClass)」形式的字符串,並且不知道它來自哪個程序集,創建該對象實例的最簡單方法是什麼?從名字中實例化一個泛型的最好方法是什麼?

如果有幫助,我知道該類實現IMyCustomInterface並且來自加載到當前AppDomain中的程序集。

Markus Olsson舉了一個很好的例子here,但我不明白如何將它應用到泛型。

回答

7

解析完成後,請使用Type.GetType(string)來獲取涉及的類型的引用,然後使用Type.MakeGenericType(Type[])構造所需的特定泛型類型。然後,使用Type.GetConstructor(Type[])獲得對特定泛型的構造函數的引用,最後調用ConstructorInfo.Invoke來獲取對象的實例。

Type t1 = Type.GetType("MyCustomGenericCollection"); 
Type t2 = Type.GetType("MyCustomObjectClass"); 
Type t3 = t1.MakeGenericType(new Type[] { t2 }); 
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes); 
object obj = ci.Invoke(null); 
1

如果你不介意的話翻譯成VB.NET,這樣的事情應該工作

foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) 
{ 
    // find the type of the item 
    Type itemType = assembly.GetType("MyCustomObjectClass", false); 
    // if we didnt find it, go to the next assembly 
    if (itemType == null) 
    { 
     continue; 
    } 
    // Now create a generic type for the collection 
    Type colType = assembly.GetType("MyCusomgGenericCollection").MakeGenericType(itemType);; 

    IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType); 
    break; 
} 
相關問題