2013-03-08 78 views
5

我想通过反射调用显式实现的接口方法(BusinessObject2.InterfaceMethod),但是当我使用以下代码尝试此操作时,Type.InvokeMember调用中出现System.MissingMethodException。非界面方法工作正常。有没有办法做到这一点?谢谢。如何使用Type.InvokeMember来调用一个显式实现的接口方法?

using System; 
using System.Reflection; 
using System.Runtime.InteropServices; 
using System.Text; 

namespace Example 
{ 
    public class BusinessObject1 
    { 
     public int ProcessInput(string input) 
     { 
      Type type = Assembly.GetExecutingAssembly().GetType("Example.BusinessObject2"); 
      object instance = Activator.CreateInstance(type); 
      instance = (IMyInterface)(instance); 
      if (instance == null) 
      { 
       throw new InvalidOperationException("Activator.CreateInstance returned null. "); 
      } 

      object[] methodData = null; 

      if (!string.IsNullOrEmpty(input)) 
      { 
       methodData = new object[1]; 
       methodData[0] = input; 
      } 

      int response = 
       (int)(
        type.InvokeMember(
         "InterfaceMethod", 
         BindingFlags.InvokeMethod | BindingFlags.Instance, 
         null, 
         instance, 
         methodData)); 

      return response; 
     } 
    } 

    public interface IMyInterface 
    { 
     int InterfaceMethod(string input); 
    } 

    public class BusinessObject2 : IMyInterface 
    { 
     int IMyInterface.InterfaceMethod(string input) 
     { 
      return 0; 
     } 
    } 
} 

异常详细信息:“Method'Example.BusinessObject2.InterfaceMethod'not found。”

+2

'type'应类型的接口,那么'instance'在InvokeMember应该是你的类的实例。现在看起来'type'是针对你的课程的,而不是你的接口。 – vcsjones 2013-03-08 14:24:00

+0

@vcsjones除了在调用CreateInstance之外,它需要是具体类型,而不是接口。但基本上:是的,你说什么 – 2013-03-08 14:25:30

+0

OK,CreateInstance已经使用了具体类型,所以没有改变。我不确定InvokeMember中的哪个实例应该是您班级的一个实例。“手段。请你能详细说明/提供一些示例代码吗? – Polyfun 2013-03-08 14:36:06

回答

3

这是由BusinessObject2明确实施IMyInterface这一事实引起的。您需要使用IMyInterface类型来访问,并随后调用的方法:

int response = (int)(typeof(IMyInterface).InvokeMember(
        "InterfaceMethod", 
        BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, 
        null, 
        instance, 
        methodData)); 
+0

这给了我例外的“方法”Example.IMyInterface.InterfaceMethod'未找到。“ – Polyfun 2013-03-08 14:32:44

+1

我还需要为您的更改添加BindingFlags.Public工作。谢谢。 – Polyfun 2013-03-08 14:39:08

+0

@ShellShock谢谢,回复更新。 – 2013-03-08 16:17:25

相关问题