我有一个类,那个类'class1'正在实现一个接口interface1
我需要使用反射调用类中的方法.
我不能使用类名和接口名,因为这两个名称都会动态改变
interface1 objClass = (interface1 )FacadeAdapterFactory.GetGeneralInstance("Class"+ version);
请参阅上面的代码段.类名和接口名称应根据其版本进行更改.我通过使用创建了类的实例
Activator.CreateInstance(Type.GetType("Class1"))
Run Code Online (Sandbox Code Playgroud)
但是我不能为接口创建相同的东西
有没有办法实现上述背景.
你不能创建接口的实例,只是实现接口的类.有一些方法可以从接口中提取方法(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);
Run Code Online (Sandbox Code Playgroud)
我希望这已经足够了.
| 归档时间: |
|
| 查看次数: |
4856 次 |
| 最近记录: |