Call the method by using the number of expressions and the number of expressions
Using the expression tree to build a delegate to improve reflection performance makes a small change, which is suitable for your use.
public static class DynamicMethodBuilder { public static Delegate BuildDynamicDelegate(MethodInfo methodInfo, ConstructorInfo constructorInfo = null) { if (methodInfo == null) throw new ArgumentNullException("methodInfo"); List<ParameterExpression> paramExpressions = methodInfo.GetParameters().Select((p, i) => { var name = "param" + (i + 1); return Expression.Parameter(p.ParameterType, name); }).ToList(); MethodCallExpression callExpression; if (methodInfo.IsStatic) { //Call(params....) callExpression = Expression.Call(methodInfo, paramExpressions); } else { if (constructorInfo != null) { //Instance(params).Call(params....) List<ParameterExpression> constructorParamExpressions = constructorInfo.GetParameters().Select((p, i) => { var name = "constparam" + (i + 1); return Expression.Parameter(p.ParameterType, name); }).ToList(); callExpression = Expression.Call(Expression.New(constructorInfo, constructorParamExpressions), methodInfo, paramExpressions); paramExpressions.InsertRange(0, constructorParamExpressions); } else { callExpression = Expression.Call(Expression.New(methodInfo.ReflectedType), methodInfo, paramExpressions); } } return Expression.Lambda(callExpression, paramExpressions).Compile(); } }
Test:
Public class Baby {private readonly DateTime _ birthDay; public Baby (DateTime birthDay) {_ birthDay = birthDay;} public Baby () {_ birthDay = DateTime. now;} public string GetBabyInfo (string name, int sex) =>$ "name: {name}, Date of Birth: {DateTime. now-_ birthDay}, Gender: {(sex = 1? "Male": "female")} ";} class Program {static void Main (string [] args) {Type targetType = Assembly. getExecutingAssembly (). getType ("leleapplication1.baby"); MethodInfo methodInfo = targetType. getMethod ("GetBabyInfo", new [] {typeof (string), typeof (int)}); ConstructorInfo constructor = targetType. getConstructor (new [] {typeof (DateTime)}); WithConstructor (methodInfo, constructor); WithOutConstructor (methodInfo); Console. readKey ();} static void WithConstructor (MethodInfo methodInfo, ConstructorInfo constructor) {var func = (Func <DateTime, string, int, string>) DynamicMethodBuilder. buildDynamicDelegate (methodInfo, constructor); Console. writeLine (func (DateTime. now. addDays (-100), "Sugar Pier", 1);} static void WithOutConstructor (MethodInfo methodInfo) {var func = (Func <string, int, string>) DynamicMethodBuilder. buildDynamicDelegate (methodInfo); Console. writeLine (func ("Sugar Pier", 1 ));}}