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
でしょうか?