¿Cómo crear un delegado a partir de un MethodInfo cuando la firma del método no se puede conocer de antemano?
Necesito un método que tome unMethodInfo
instancia que representa un método estático no genérico con firma arbitraria y devuelve un delegado vinculado a ese método que podría invocarse más tarde usandoDelegate.DynamicInvoke
método. Mi primer intento ingenuo se veía así:
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.
}
}
Esperaba que elMethodInfo.CreateDelegate
El método podría averiguar el tipo correcto de delegado. Bueno, obviamente no puede. Entonces, ¿cómo creo una instancia deSystem.Type
representando a un delegado con una firma que coincida con la proporcionadaMethodInfo
¿ejemplo?