Подтвердить что ты не робот

Как я могу создать делегат Action из MethodInfo?

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

4b9b3361

Ответ 1

Используйте 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);

Ответ 2

Это похоже на работу над советом Джона:

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;
    }
}