42

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

4

2 に答える 2

37

System.Linq.Expressions.Expression.GetDelegateTypeメソッドを使用できます。

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

class Program
{
    static void Main()
    {
        var writeLine = CreateDelegate(typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }));
        writeLine.DynamicInvoke("Hello world");

        var readLine = CreateDelegate(typeof(Console).GetMethod("ReadLine", Type.EmptyTypes));
        writeLine.DynamicInvoke(readLine.DynamicInvoke());
    }

    static Delegate CreateDelegate(MethodInfo method)
    {
        if (method == null)
        {
            throw new ArgumentNullException("method");
        }

        if (!method.IsStatic)
        {
            throw new ArgumentException("The provided method must be static.", "method");
        }

        if (method.IsGenericMethod)
        {
            throw new ArgumentException("The provided method must not be generic.", "method");
        }

        return method.CreateDelegate(Expression.GetDelegateType(
            (from parameter in method.GetParameters() select parameter.ParameterType)
            .Concat(new[] { method.ReturnType })
            .ToArray()));
    }
}

の 2 番目のチェックでおそらくコピーと貼り付けのエラーが発生し!method.IsStaticます。そこでは使用しないでくださいArgumentNullException。また、 への引数としてパラメータ名を提供するのは良いスタイルArgumentExceptionです。

method.IsGenericMethodすべてのジェネリック メソッドを拒否するmethod.ContainsGenericParameters場合、および置換されていない型パラメーターを持つジェネリック メソッドのみを拒否する場合に使用します。

于 2013-05-03T17:05:57.720 に答える
4

System.LinQ.Expressions を試してみてください

...
using System.Linq.Expressions;
...

static Delegate CreateMethod(MethodInfo method)
{
    if (method == null)
    {
        throw new ArgumentNullException("method");
    }

    if (!method.IsStatic)
    {
        throw new ArgumentException("The provided method must be static.", "method");
    }

    if (method.IsGenericMethod)
    {
        throw new ArgumentException("The provided method must not be generic.", "method");
    }

    var parameters = method.GetParameters()
                           .Select(p => Expression.Parameter(p.ParameterType, p.Name))
                           .ToArray();
    var call = Expression.Call(null, method, parameters);
    return Expression.Lambda(call, parameters).Compile();
}

後で次のように使用します

var method = CreateMethod(typeof (Console).GetMethod("WriteLine", new[] {typeof (string)}));
method.DynamicInvoke("Test Test");
于 2013-05-03T17:16:55.593 に答える