How to use Type.InvokeMember to call an explicitly implemented interface method?

I want to call an explicitly implemented interface method (BusinessObject2.InterfaceMethod) using reflection, but when I try to use this code, I get a System.MissingMethodException message to call Type.InvokeMember. Non-interface methods work fine. Is there any way to do this? Thank.

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;
        }
    }
}

Exception Details: "Method" Example.BusinessObject2.InterfaceMethod "not found".

+5
source share
1 answer

This is because it BusinessObject2explicitly implements IMyInterface. You need to use a type IMyInterfaceto access and subsequently call the method:

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

All Articles