Hi I\'m trying to create a function that dynamically creates a delegate with the same return value and the same parameters as a MethodInfo it receives as parameter and also
I have just stumbled upon a nice way to solve this issue, it looks like this for delegates to a static method:
private static Delegate CreateDelegate(MethodInfo method) {
var paramTypes = method.GetParameters().Select(p => p.ParameterType);
Type delegateType = Expression.GetDelegateType(paramTypes.Append(method.ReturnType).ToArray());
return Delegate.CreateDelegate(delegateType, method, true);
}
It uses this extension method:
public static IEnumerable Append(this IEnumerable collection, TSource element) {
if (collection == null) throw new ArgumentNullException("collection");
foreach (TSource element1 in collection) yield return element1;
yield return element;
}