【问题标题】:How can I create an Action delegate from MethodInfo?如何从 MethodInfo 创建 Action 委托?
【发布时间】:2011-03-02 14:00:56
【问题描述】:

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

【问题讨论】:

    标签: .net action methodinfo


    【解决方案1】:

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

    【讨论】:

    • 赞成。如何将此应用于 DataEventArgs ? stackoverflow.com/questions/33376326/…
    • Delegate.CreateDelegate 在 .Net Core 中似乎不可用。有什么想法吗?
    • @IAbstract:有趣-我没有发现。您可以致电 MethodInfo.CreateDelegate。 (刚刚试了一下,效果很好。)
    • @JonSkeet:是的,实际上发现并感谢添加答案。 +1 完整性!!!
    • @IAbstract:这听起来很奇怪。可能会在一个新问题中提出这个问题?
    【解决方案2】:

    这似乎也符合 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2015-02-09
      • 2017-07-02
      相关资源
      最近更新 更多