我想通过反射调用显式实现的接口方法 (BusinessObject2.InterfaceMethod),但是当我使用以下代码尝试此操作时,我得到 Type.InvokeMember 调用的 System.MissingMethodException。非接口方法工作正常。有没有办法做到这一点?谢谢。
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;
}
}
}
异常详细信息:“找不到方法'Example.BusinessObject2.InterfaceMethod'。”