You can do this using the following method. Note: you cannot create a generic Action<...> using this method, because, as you say, types are not known at compile time. But it is pretty close.
public delegate void DynamicInvokeDelegate(params object[] args); public static DynamicInvokeDelegate CreateDynamicInvokeDelegate(MethodInfo method, object instance) { return args => method.Invoke(instance, args); }
If you need the delegate to return a value:
public delegate object DynamicInvokeWithReturnDelegate(params object[] args); public static DynamicInvokeWithReturnDelegate CreateDynamicInvokeWithReturnDelegate(MethodInfo method, object instance) { return args => method.Invoke(instance, args); }
EDIT:
It actually looks like you might need this code:
public static T GetDelegate<T>(MethodInfo method, object instance) where T : class { return (T)(object)Delegate.CreateDelegate(typeof(T), instance, method); }
A cast is required because the compiler will not allow you to use Delegate for any random type, and you cannot restrict T to a delegate. Casting through an object satisfies the compiler.
source share