Como criar um delegado de um MethodInfo quando a assinatura do método não pode ser conhecida antecipadamente?

Eu preciso de um método que leve umMethodInfo instância representando um método estático não genérico com assinatura arbitrária e retorna um delegado ligado a esse método que poderia ser invocado posteriormente usandoDelegate.DynamicInvoke método. Minha primeira tentativa ingênua ficou assim:

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.
    }
}

Eu esperava que oMethodInfo.CreateDelegate método poderia descobrir o tipo de delegado correto em si. Bem, obviamente não pode. Então, como eu crio uma instância deSystem.Type representando um delegado com uma assinatura correspondente ao fornecidoMethodInfo instância?

questionAnswers(2)

yourAnswerToTheQuestion