Saturday, June 1, 2019

C Sharp : Invoking a method dynamically using a name of method string

Here's my attempts to dynamically call a method using just the name of the method as a string. 

The examples below will call a method within the same class. 

Here's method signature I am trying to invoke
1
public void GetText(object sender, EventArgs e) //sender is a menuitem

1 st attempt
1
2
string methodName = "GetText"; 
Action<string> myAction = new Action<string>(methodName);

Error : methodName is a variable but used like a method

2nd attempt
1
2
string methodName = "GetText"; 
Func<string, string> funky = new Func<string, string>(methodName);

Error : methodName is a variable but used like a method

3rd attempt

1
2
3
4
5
6
7
8
                string methodName = "GetText";
                Type callerType = this.GetType();
                string output = (string)callerType.InvokeMember(
                methodName,
                BindingFlags.InvokeMethod,
                null,
                null,
                null);  

Error Method 'Program.Class.methodName' not found. Issue args does not match the method signature.


4th attempt - Correct method args
1
2
3
4
5
6
7
string output = (string)callerType.InvokeMember(
 methodName,
 BindingFlags.InvokeMethod,
 null,
 null,
 new Object[] { sender, e }
);

Error "Non-static method requires a target. Issue incorrect return type, this case it must be void.


5th attempt - works but

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//create instance assuming default constructor
object obj = callerType.InvokeMember(null, BindingFlags.Public |
BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);

callerType.InvokeMember(
 methodName,
 BindingFlags.InvokeMethod,
 null,
 obj, //this created whole new menu!
 new Object[] { menuItemMRU, e }); //sender need to be menuItem

Error oops this creates a entire new object, in this case a new menu.

6th attempt - working properly. Perhaps read this daunting MS doc first. 


1
2
3
4
5
6
7
this.GetType().InvokeMember(
 methodName,
 BindingFlags.InvokeMethod | BindingFlags.Instance,
 null,
 this, //<-THIS indicatates it being called by this program, class instantiation
 new object[] { menuItemMRU, e } //args to pass, we are faking a menu-item
 );

No comments:

Post a Comment