Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoke non static method by name

I've been trying to invoke a method by name but the problem is the method I invoke cannot be static and it needs to be of the current class.

I've tried the way of doing it like this:

public static void InvokeMenuMethod(string methodName, object sender, EventArgs e)
  Type calledType = Type.GetType("MyNamespace.MyClass");
  calledType.InvokeMember(
    methodName,
    BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
    null,
    null,
    new object[] { sender, e }
  );
}

This obviously only works for static members so I tried something like this

public static void InvokeMenuMethod(string methodName, object sender, EventArgs e)
  Type calledType = Type.GetType("this");
  calledType.InvokeMember(
    methodName,
    BindingFlags.InvokeMethod | BindingFlags.Public,
    null,
    null,
    new object[] { sender, e }
  );
}

But I get Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty). Parameter name: bindingFlags error...

So how can I go about doing this?

EDIT:

So:

public void InvokeMenuMethod(string methodName, object sender, EventArgs e) {
    Type.GetType("this").InvokeMember(
        methodName,
        BindingFlags.InvokeMethod,
        null,
        this,
        new object[] { sender, e }
    );
}

Gives a NullReferenceException

Solution: No "this" in Type.GetType("this")

like image 399
Mark Lalor Avatar asked Feb 02 '23 14:02

Mark Lalor


1 Answers

try

 this.GetType().InvokeMember(
    methodName,
    BindingFlags.InvokeMethod,
    null,
    this,
    new object[] { sender, e }
  );

From MSDN

If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included

like image 193
Yahia Avatar answered Feb 05 '23 03:02

Yahia