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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With