加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用Type.InvokeMember来调用显式实现的接口方法?

发布时间:2020-12-15 05:38:26 所属栏目:百科 来源:网络整理
导读:我想通过反射调用一个显式实现的接口方法(BusinessObject2.InterfaceMethod),但是当我使用下面的代码尝试这个时,我得到一个Type.InvokeMember调用的System.MissingMethodException.非接口方法可以正常工作.有没有办法做到这一点?谢谢. using System;using S
我想通过反射调用一个显式实现的接口方法(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.”

解决方法

这是因为BusinessObject2显式实现了IMyInterface.您需要使用IMyInterface类型来访问并随后调用该方法:
int response = (int)(typeof(IMyInterface).InvokeMember(
                    "InterfaceMethod",BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,methodData));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读