【发布时间】:2011-03-02 14:00:56
【问题描述】:
我想从 MethodInfo 对象中获取操作委托。这可能吗?
【问题讨论】:
标签: .net action methodinfo
我想从 MethodInfo 对象中获取操作委托。这可能吗?
【问题讨论】:
标签: .net action methodinfo
// 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);
【讨论】:
Delegate.CreateDelegate 在 .Net Core 中似乎不可用。有什么想法吗?
MethodInfo.CreateDelegate。 (刚刚试了一下,效果很好。)
这似乎也符合 John 的建议:
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;
}
}
【讨论】: