So the obvious way to do this is..
var handler = GetType().GetMethod(methodName, BindingFlags.NonPublic |
BindingFl
The fastest way would be to cache a typed delegate; if you know the signature is always:
void PersonInstance.MethodName(string s);
Then you could create an Action
via Delegate.CreateDelegate:
var action = (Action)Delegate.CreateDelegate(
typeof(Action), method);
This can then be cached against the name, and invoked as:
action(personInstance, value);
Note that the cache here is critical; the reflection to locate the method and prepare a typed-delegate is non-trivial.
It gets harder if the signature is unpredictable, as DynamicInvoke is relatively slow. The fastest way would be to use DynamicMethod and ILGenerator to write a shim method (on the fly) that takes an object[] for the parameters and unpacks and casts it to match the signature - then you can store an Action
or Func
. That is, however, an advanced topic. I could provide an example if really needed. Essentially writing (at runtime):
void DummyMethod(object target, object[] args) {
((Person)target).MethodName((int)args[0],(string)args[1]);
}
Here's an example of doing that (note: it doesn't handle ref
/out
args at the moment, and possibly a few other scenarios - and I've left the "cache" side of things as an exercise for the reader):
using System;
using System.Reflection;
using System.Reflection.Emit;
class Program
{
static void Main()
{
var method = typeof(Foo).GetMethod("Bar");
var func = Wrap(method);
object[] args = { 123, "abc"};
var foo = new Foo();
object result = func(foo, args);
}
static Func