公告
财富商城
积分规则
提问
发文
2019-01-14 00:32发布
手持菜刀,她持情操
I want to get an action delegate from a MethodInfo object. Is this possible?
Thank you.
This seems to work on top of John's advice too:
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; } }
Use 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);
For an Action<T> etc, just specify the appropriate delegate type everywhere.
Action<T>
In .NET Core, Delegate.CreateDelegate doesn't exist, but MethodInfo.CreateDelegate does:
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);
最多设置5个标签!
This seems to work on top of John's advice too:
Use Delegate.CreateDelegate:
For an
Action<T>
etc, just specify the appropriate delegate type everywhere.In .NET Core,
Delegate.CreateDelegate
doesn't exist, butMethodInfo.CreateDelegate
does: