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."
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With