简体   繁体   中英

Why does it not execute the method with reflection

I am trying to execute a method in a class from within it with reflection. Althoough the method exists, I am still getting the 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( ) { }

Maybe it it worth to say that this methods are situated in a base class and the ExecuteMethod is beingcalled on the child Class. I don't think it should matter, but anyway.

From the documentation :

You must specify Instance or Static along with Public or NonPublic or no members will be returned.

From the code it seems that in your case the method is static , so add BindingFlags.Static .

You have specified the method to execute, but not which object to execute it on. You cannot just execte something on a type , you need to specify a concrete object. You use the type to get the metadata of the method, then that information is used to invoke the method on an actual object. Check this MSDN page for more details.

That second to last null should be the object, probably this in your case.

Try sending a instance of the object that has the method

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

this is another way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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