我需要一个方法,该方法接受一个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 …
Run Code Online (Sandbox Code Playgroud)