繁体   English   中英

为什么它不用反射执行方法

[英]Why does it not execute the method with reflection

我试图用反射在一个类中执行一个方法。 虽然该方法存在,但我仍然得到MethodNotFound Exception

public virtual void ExecuteMethod(string MethodName) 
    {
        if(this is ISelectable)
        {
            Type thisType = (this as ISelectable).GetType();
            thisType.InvokeMember(MethodName, BindingFlags.InvokeMethod | BindingFlags.Public , null, null, null);
        }
    }

    public virtual void Add( ) { }

也许值得一提的是,这些方法位于基类中,而ExecuteMethod则在子类上进行调用。 我认为这不重要,但无论如何。

文档

您必须与PublicNonPublic一起指定InstanceStatic ,否则将不返回任何成员。

从代码看来,在你的情况下,方法是static ,所以添加BindingFlags.Static

您已指定要执行的方法 ,但未指定要在其上执行的对象 你不仅可以在类型上执行某些操作,还需要指定具体对象。 您使用该类型来获取方法的元数据,然后该信息用于在实际对象上调用该方法。 请查看此MSDN页面以获取更多详细信息。

这倒数第二个null应该是对象,可能this在你的情况。

尝试发送具有该方法的对象的实例

thisType.InvokeMember(MethodName, BindingFlags.InvokeMethod | BindingFlags.Public, null
    , this // instance of the object which has the method
    , null);

这是另一种方式

MethodInfo _methodinfo= type.GetMethod(MethodName);
_methodinfo.Invoke(null, null)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM