43

我想从 MethodInfo 对象中获取操作委托。这可能吗?

4

2 回答 2

73

使用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);
于 2010-06-11T09:14:16.220 回答
1

这似乎也适用于约翰的建议:

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;
    }
}
于 2012-06-17T17:09:11.073 回答