For creating delegates on the fly, techniques vary from Delegate.CreateDelegate, to Expresion Lambda, DynamicMethod, etc. etc. All of these techniques require that you know the type of the delegate.
I'm trying to convert closed delegates to open delegates generically, and to do to achieve this it seems I need to dynamically create the type of the open delegate before I can actually create the resulting delegate. Consider:
pubic class WeakEvent<TDelegate> where TDelegate : class
{
public WeakEvent(Delegate aDelegate)
{
var dgt = aDelegate as TDelegate;
if(dgt == null)
throw new ArgumentException("aDelegate");
MethodInfo method = dgt.Method;
var parameters = Enumerable
.Repeat(dgt.Target.GetType(),1)
.Concat(method.GetParameters().Select(p => p.ParameterType));
Type openDelegateType = // ??? original delegate, with new 1st arg for @this
var dm = new DynamicMethod("InnerCode", method.ReturnType, parameters);
... your favourite IL code emmisions go here
var openDelegate = dm.CreateDelegate(openDelegateType);
}
}
The purpsoe of the above code is to create a new delegate which is identical to the original delegate, but has a new 1st argument for this... i.e. an open version of the previously closed delegate.
Is there a simple way to clone & modify an existing delegate type, or is the nearest solution to build out the generic Func<> and Action<> types?