I need a method that takes a MethodInfo
instance representing a non-generic static method with arbitrary signature and returns a delegate bound to that method that could later be invoked using Delegate.DynamicInvoke
method. My first naïve try looked like this:
using System;
using System.Reflection;
class Program
{
static void Main()
{
var method = CreateDelegate(typeof (Console).GetMethod("WriteLine", new[] {typeof (string)}));
method.DynamicInvoke("Hello world");
}
static Delegate CreateDelegate(MethodInfo method)
{
if (method == null)
{
throw new ArgumentNullException("method");
}
if (!method.IsStatic)
{
throw new ArgumentNullException("method", "The provided method is not static.");
}
if (method.ContainsGenericParameters)
{
throw new ArgumentException("The provided method contains unassigned generic type parameters.");
}
return method.CreateDelegate(typeof(Delegate)); // This does not work: System.ArgumentException: Type must derive from Delegate.
}
}
I hoped that the MethodInfo.CreateDelegate
method could figure out the correct delegate type itself. Well, obviously it cannot. So, how do I create an instance of System.Type
representing a delegate with a signature matching the provided MethodInfo
instance?
You can use System.Linq.Expressions.Expression.GetDelegateType method:
There is probably a copy-paste error in the 2nd check for
!method.IsStatic
- you shouldn't useArgumentNullException
there. And it is a good style to provide a parameter name as an argument toArgumentException
.Use
method.IsGenericMethod
if you want to reject all generic methods andmethod.ContainsGenericParameters
if you want to reject only generic methods having unsubstituted type parameters.You may want to try System.LinQ.Expressions
and use it later as following