Мне нужен метод, который принимает экземпляр MethodInfo
, представляющий неэквивалентный статический метод с произвольной сигнатурой, и возвращает делегат, связанный с этим методом, который позже может быть вызван с использованием метода Delegate.DynamicInvoke
. Моя первая наивная попытка выглядела так:
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.
}
}
Я надеялся, что метод MethodInfo.CreateDelegate
может определить правильный тип делегата. Ну, очевидно, это невозможно. Итак, как мне создать экземпляр System.Type
, представляющий делегат с подписью, соответствующей предоставленному экземпляру MethodInfo
?