Create a delegate with arbitrary parameters

I have a System.Reflection.MethodInfo and would like to have a method that creates a delegate (preferably Func <...> or Action <...>) that represents this method, given the instance to call it is included.

Ideally, I would like something like the following psuedo code:

public TDelegate GetMethod<TDelegate>(MethodInfo methodToRepresent, object instanceToInvokeOn) { return (TDelegate)((parameters....) => methodToRepresent.Invoke(instanceToInvokeOn, all parameters in an object[])); } 

where TDelegate represents the signature of the method presented. If the signatures do not match, an exception should be thrown.

I understand that I probably cannot achieve this with a simple lambda expression, since its parameters must be known at compile time. Maybe I need to build a delegate from scratch? Is it possible to create a delegate by specifying its body and parameters separately?

thanks

+4
source share
2 answers

I do not understand your question. But maybe you want this:

 public TDelegate GetMethod<TDelegate>(MethodInfo methodToRepresent, object instanceToInvokeOn) where TDelegate:class { return (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), instanceToInvokeOn, methodToRepresent); } 
+3
source

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.

+2
source

All Articles