我有一个类,'class1‘类实现了一个接口interface1
我需要使用反射在类中调用一个方法。
我不能直接使用类名和接口名,因为这两个名称都会动态更改。
interface1 objClass = (interface1 )FacadeAdapterFactory.GetGeneralInstance("Class"+ version);
请参见上面的代码片段。类名称和接口名称应根据其版本进行更改。我已经使用以下命令为class创建了实例
Activator.CreateInstance(Type.GetType("Class1"))
但是,我不能为接口编写同样的内容。
有没有办法实现上面的上下文。
发布于 2012-02-17 18:44:23
你不能创建接口的实例,只能创建实现接口的类。有一些方法可以从接口中提取方法(info)。
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);
我希望这足够了。
https://stackoverflow.com/questions/9326227
复制相似问题