Reputation: 8780
I have a chart, and I have a tree view with nodes that when selected bring up various charts. The tree view nodes are named xxxChart, and the methods that bring up the various charts are named xxxChart after whichever node that calls it.
There are parameters that can be changed (start/end date for example) and when that happens I need to run the method for the current chart again to refresh it with the updated parameter selection. I thought it would be a good idea to have an Action object called DisplayChart that would be set whenever a node is selected. Then when a parameter is changed I just call DisplayChart().
Now, I welcome any ideas you may have for better patterns to solve this problem but my question is this: How can I use reflection to get something I can assign to the Action object? I know how to invoke a method using reflection, but when a node is selected I just want to store the method with the name matching that node in the DisplayChart Action object.
Of course, I know I could just use a MethodInfo object instead of an Action object and then use reflection to invoke the method, but I'm still curious how to do it this way.
Upvotes: 2
Views: 1684
Reputation: 113402
Relying on method naming conventions and reflection isn't very robust, but to answer your question directly, you can use one of the overloads of Delegate.CreateDelegate
.
E.g.
object boundObject = ...
MethodInfo method = ...
Action action = (Action)Delegate.CreateDelegate(typeof(Action),
boundObject,
method);
Upvotes: 3