static Expression[] buildParameters(Type[] parameterTypes, ParameterExpression paramExp) { List <Expression> list = new List <Expression>(); for (int i = 0; i < parameterTypes.Length; i++) { var arg = BinaryExpression.ArrayIndex(paramExp, Expression.Constant(i)); var argCast = Expression.Convert(arg, parameterTypes[i]); list.Add(argCast); } return(list.ToArray()); }
static Expression[] BuildParameters(Type[] parameterTypes, ParameterExpression paramExp) { List <Expression> list = new List <Expression>(); for (int i = 0; i < parameterTypes.Length; i++) { //从参数表达式(参数是:object[])中取出参数 var arg = BinaryExpression.ArrayIndex(paramExp, Expression.Constant(i)); //把参数转化成指定类型 var argCast = Expression.Convert(arg, parameterTypes[i]); list.Add(argCast); } return(list.ToArray()); }
/// <summary> /// 搜索其参数与指定数组中的类型匹配的公共实例构造函数,并返加该构造函数的委托 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type">类型</param> /// <param name="parameterTypes">指定参数数组</param> /// <returns></returns> public static Func <object[], T> CreateInstanceDelegate <T>(this Type type, params Type[] parameterTypes) { //根据参数类型数组来获取构造函数 var constructor = type.GetConstructor(parameterTypes); //创建lambda表达示参数 var lambdaParamsExp = Expression.Parameter(typeof(object[]), "_args"); //转换参数为构造函数可用的类型 var paramsExp = new Expression[parameterTypes.Length]; for (int i = 0; i < parameterTypes.Length; ++i) { var oneParamExp = BinaryExpression.ArrayIndex(lambdaParamsExp, Expression.Constant(i, typeof(int))); paramsExp[i] = Expression.Convert(oneParamExp, parameterTypes[i]); } //创建构造函数表达式 var newExp = Expression.New(constructor, paramsExp); //创建Func<object[],object>并返回 return(Expression.Lambda <Func <object[], T> >(newExp, lambdaParamsExp).Compile()); }
static Expression getMethodCallExpression(MethodInfo method, Type controllerType, Expression c, Expression ps) { var parameters = method.GetParameters(); Expression[] pExps = new Expression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { var pinfo = parameters[i]; var valExp = BinaryExpression.ArrayIndex(ps, Expression.Constant(i)); if (pinfo.ParameterType != typeof(object)) { pExps[i] = Expression.Convert(valExp, pinfo.ParameterType); } else { pExps[i] = valExp; } } var exp = Expression.Call(c, controllerType.GetMethod(method.Name), pExps); return(exp); }