So the obvious way to do this is..
var handler = GetType().GetMethod(methodName, BindingFlags.NonPublic |
BindingFlags.Instance);
handler.Invoke(this, new object[] {e});
And I can add caching to keep the methods around but I’m wondering if there is a completely different and faster way?
The fastest way would be to cache a typed delegate; if you know the signature is always:
Then you could create an
Action<Person,string>via Delegate.CreateDelegate:This can then be cached against the name, and invoked as:
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<object, object[]>orFunc<object,object[],object>. That is, however, an advanced topic. I could provide an example if really needed. Essentially writing (at runtime):Here’s an example of doing that (note: it doesn’t handle
ref/outargs at the moment, and possibly a few other scenarios – and I’ve left the “cache” side of things as an exercise for the reader):