In my last post, I showed a nifty way of constructing "early-bound" delegates using LCG. Here's the same helper class implemented without LCG:
public static class DelegateBinder { public static TDelegate Bind<TDelegate>(object firstArg, MethodInfo method) { return (TDelegate)Activator.CreateInstance( typeof(TDelegate), firstArg, method.MethodHandle.GetFunctionPointer()); } }
This one is quite a bit simpler, and extrapolating from what we learned last time, it's easy to see what's happening. Hopefully, you are already familiar with the Activator class. Basically, this just shows the managed call chain that produces a function pointer to a method given a MethodInfo.
I really like the LCG-based implementation, but only because of my love of DynamicMethod. It's pretty complex, and aside from opportunities for caching, doesn't really have anything over this implementation. This one is just plain simple, and would have a single-line implementation if I hadn't put some line breaks to avoid formatting problems. It does, however, highlight the annoyingness of having to work around the compilers' "helpfulness" when it comes to delegate construction. If only I could just call the constructor directly.
It is worth noting that this doesn't work in the Silverlight 1.1 alpha or the compact framework (or XNA for that matter), neither of which expose RuntimeMethodHandle.GetFunctionPointer().
Remember Me
Page rendered at Wednesday, October 08, 2008 3:23:24 AM (Pacific Standard Time, UTC-08:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.