Dear sirs and ladies.
First, a little introduction.
I have to functions:
static class C
{
static void F1(Type type)
{
// Do something to invoke F2<T>
}
static void F2<T>()
{
// bla bla bla
}
}
I wish to invoke F1(Type)
, which in turn should transition to the generic context pertinent to the given type parameter and invoke the generic counterpart F2<T>
.
A naive implementation would be a simple reflection, like this (I omit binding flags for clarity):
void F1(Type type)
{
var f2MethodInfo = typeof(C).GetMethod("F2").MakeGenericMethod(type);
f2MethodInfo.Invoke(null, new object[0]);
}
A more advanced implementation would store the open method info for F2 - typeof(C).GetMethod("F2")
aside, but still it is basically the same thing.
If F1
is invoked many times and we wish to improve the performance, then the standard solution "on the market" employs a dictionary and Delegate.CreateDelegate
method, like this:
IDictionary<Type, Action> m_cache = new Dictionary<Type, Action>();
MethodInfo F2MethodInfo = typeof(C).GetMethod("F2");
void F1(Type type)
{
Action action;
if (!m_cache.TryGetValue(type, out action))
{
m_cache[type] = action = (Action)Delegate.CreateDelegate(typeof(Action), F2MethodInfo.MakeGenericMethod(type));
}
action();
}
And now to my question. Is it possible to eliminate the dictionary completely?
For instance, by emitting some fancy function with Reflection.Emit which would receive a Type instance and F2MethodInfo and make the transition inside without and dictionaries? This fancy function should be emitted just once and work for any given type. I wonder if any kind of cache mapping Type to delegates can be eliminated this way.
Thanks.
EDIT
For the sake of this discussion, let us assume that the fancy emitted function knows that it should invoke F2, meaning it does not have to receive its method info. Is it possible to ditch the dictionary then?