How can I create an Action delegate from MethodInfo?

后端 未结 2 2043
旧时难觅i
旧时难觅i 2020-12-03 04:47

I want to get an action delegate from a MethodInfo object. Is this possible?

2条回答
  •  Happy的楠姐
    2020-12-03 04:58

    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 CreateDelegate(object target, MethodInfo method)
        {
            var del = (Action)Delegate.CreateDelegate(typeof(Action), target, method);
    
            return del;
        }
    }
    

提交回复
热议问题