2012-02-17 257 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