Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

I want to call an explicitly implemented interface method (BusinessObject2.InterfaceMethod) via reflection, but when I try this using the following code, I get an System.MissingMethodException for the Type.InvokeMember call. Non-interface methods work OK. Is there a way to do this? Thanks.

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."

like image 747
Polyfun Avatar asked Mar 08 '13 14:03

Polyfun


1 Answers

This is caused by the fact that BusinessObject2 explicitly implements IMyInterface. You need to use the IMyInterface type to gain access to and subsequently invoke the method:

int response = (int)(typeof(IMyInterface).InvokeMember(
                    "InterfaceMethod",
                    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
                    null,
                    instance,
                    methodData));
like image 123
Rich O'Kelly Avatar answered Oct 02 '22 22:10

Rich O'Kelly