2013-03-20 81 views
0

project1具有class1和interface1。 Class1實現了interface1。我有另一個項目將使用interface1測試這個class1方法。現在catch是我必須動態加載project1.dll並使用接口方法調用class1方法。爲此,我使用反射來加載project1.dll。現在,我從接口中獲取methodInfo,並在調用此方法之前,我應該創建一個將調用該方法的類的實例。要使用activator.createInstance創建類的實例,我需要知道構造函數參數。現在,這些構造函數參數是自定義類型。正如我前面所說,我必須動態加載dll。那麼是否有一種方法可以從組裝載入中獲取類型?或者其他任何方法來實現上述想法?以下是我的代碼。使用反射從裝配負載中獲取類型

Assembly assembly = Assembly.LoadFrom(@"D:\Project1.dll"); 
Type[] typeArray = assembly.GetTypes(); 
object obj; 

//First create the instance of the class 
foreach (Type type in typeArray) 
{ 

    if (type.Name == "Class1") 
    { 

     Type[] types = new Type[4]; 

     //I am not able to get the below customParams from the loaded assembly. 
     //Is there a way to do this. Can this be done without adding reference? 
     types[0] = typeof(CustompParam1); 
     types[1] = typeof(CustompParam2); 
     types[2] = typeof(CustompParam3); 
     types[3] = typeof(CustompParam4); 

     obj = Activator.CreateInstance(types); 
    } 
} 

//use the instance of the class to invoke the method from the interface 
foreach (Type type in typeArray) 
{ 
    if (type.Name == "Interface1") 
    { 
     MethodInfo[] mInfo = type.GetMethods(); 
     foreach (MethodInfo mi in mInfo) 
     { 
      mi.Invoke(obj, null); 
     } 
    } 
} 
+0

我假設你既不知道自定義參數類型,你的意圖是使用默認值(對於引用類型爲'null',對於值類型爲'0'等價物)調用構造函數? – 2013-03-20 13:14:39

+0

我知道自定義參數類型是什麼。但是我不能將它們的引用添加到我的項目中,我必須通過動態加載它們來獲取它們。 – Virus 2013-03-20 13:17:22

+0

您可以使用[Type.GetConstructors](http://msdn.microsoft.com/en-us/library/e687hf0d.aspx)遍歷所有可用的構造函數,直到獲得所需的構造函數。編輯:一旦你找到它,你可以調用它來創建一個實例完全繞過'Activator.CreateInstance'方法。 – 2013-03-20 13:18:52

回答

0

你可以得到構造函數的參數的情況下,你創建類的實例以同樣的方式

找到他們的類型名,調用Activator.CreateInstance的參數類型,然後把它們放到Activator.CreateInstance你原來的班級。

+0

你可以請給我一個例子/ – Virus 2013-03-20 13:18:00