2012-02-17 258 views
2

我有一個類,該類'class1'正在實現一個接口interface1如何使用反射調用接口中的方法

我需要使用反射調用類中的方法。

我不能使用類名和接口名稱,因爲它是因爲這兩個名稱會改變dynamically.`

interface1 objClass = (interface1)FacadeAdapterFactory.GetGeneralInstance("Class"+ version);

見上面的代碼片斷。類名稱和接口名稱應根據其版本進行更改。我以

Activator.CreateInstance(Type.GetType("Class1")) 

創建的類實例,但我不是能夠克里特島相同的接口

有什麼辦法來實現上述背景下。

回答

5

你不能創建接口的實例,只是實現接口的類。 有一些方法從界面中提取方法(信息)。

ISample element = new Sample(); 

Type iType1 = typeof(ISample); 
Type iType2 = element.GetType().GetInterfaces() 
    .Single(e => e.Name == "ISample"); 
Type iType3 = Assembly.GetExecutingAssembly().GetTypes() 
    .Single(e => e.Name == "ISample" && e.IsInterface == true); 

MethodInfo method1 = iType1.GetMethod("SampleMethod"); 
MethodInfo method2 = iType2.GetMethod("SampleMethod"); 
MethodInfo method3 = iType3.GetMethod("SampleMethod"); 

method1.Invoke(element, null); 
method2.Invoke(element, null); 
method3.Invoke(element, null); 

我希望這是足夠的。

+0

我不能像ISample element = new Sample();因爲名稱ISample會動態改變。我通過版本號。接口名稱將根據ISample1,ISample2等版本號進行更改... – 2012-02-17 11:33:38

+0

好的,但您可以輕鬆使用: 類型iType2 = element.GetType()。GetInterfaces() .Single(e => e .Name ==「ISample」);或 類型iType3 = Assembly.GetExecutingAssembly()。GetTypes() .Single(e => e.Name ==「ISample」&& e.IsInterface == true); 只需編輯字符串 - 「ISample」 - 用版本連接。 – Meonester 2012-02-17 12:42:05