我想从MethodInfo对象获取一个动作委托。这可能吗?
谢谢。
答案 0 :(得分:63)
// 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;
}
}