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

时间:2013-06-04 08:45:45

标签: c# exception reflection methods

我正在尝试使用反射在其中执行类中的方法。虽然该方法存在,但我仍然得到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则在子类上进行调用。我认为这不重要,但无论如何。

4 个答案:

答案 0 :(得分:1)

来自documentation

  

您必须指定InstanceStatic以及PublicNonPublic或   没有会员将被退回。

从代码中看来,在您的情况下,该方法为static,因此请添加BindingFlags.Static

答案 1 :(得分:1)

您已指定执行方法,但未指定对象执行它。您不能只在类型上执行某些操作,您需要指定具体对象。您使用该类型来获取方法的元数据,然后该信息用于在实际对象上调用该方法。 Check this MSDN page了解更多详情。

倒数第二个null应该是对象,可能是this

答案 2 :(得分:1)

尝试发送具有方法

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

答案 3 :(得分:0)

这是另一种方式

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