如何从MethodInfo创建Action委托?

时间:2010-06-11 09:12:14

标签: .net action methodinfo

我想从MethodInfo对象获取一个动作委托。这可能吗?

谢谢。

2 个答案:

答案 0 :(得分:63)

使用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);

答案 1 :(得分:0)

这似乎也超出了约翰的建议:

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