Как я могу создать делегат Action из MethodInfo? - PullRequest
35 голосов
/ 11 июня 2010

Я хочу получить делегат действия от объекта MethodInfo. Возможно ли это?

Спасибо.

Ответы [ 2 ]

63 голосов
/ 11 июня 2010

Использование Delegate.CreateDelegate :

// Static method
Action action = (Action) Delegate.CreateDelegate(typeof(Action), method);

// Instance method (on "target")
Action action = (Action) Delegate.CreateDelegate(typeof(Action), target, method);

Для Action<T> и т. Д. Просто укажите соответствующий тип делегата везде.

В .NET Core, Delegate.CreateDelegate не существует, но MethodInfo.CreateDelegate существует:

// Static method
Action action = (Action) method.CreateDelegate(typeof(Action));

// Instance method (on "target")
Action action = (Action) method.CreateDelegate(typeof(Action), target);
0 голосов
/ 17 июня 2012

Похоже, это работает поверх совета Джона:

public static class GenericDelegateFactory
{
    public static object CreateDelegateByParameter(Type parameterType, object target, MethodInfo method) {

        var createDelegate = typeof(GenericDelegateFactory).GetMethod("CreateDelegate")
            .MakeGenericMethod(parameterType);

        var del = createDelegate.Invoke(null, new object[] { target, method });

        return del;
    }

    public static Action<TEvent> CreateDelegate<TEvent>(object target, MethodInfo method)
    {
        var del = (Action<TEvent>)Delegate.CreateDelegate(typeof(Action<TEvent>), target, method);

        return del;
    }
}
...