private void Test2() { var Parsing = new ParsingExpressionTrees(); Expression <Func <People, Student, Boolean> > where = (p, s) => (p.Amount > 4000 || s.Amount < 400) && p.Name.Length > 3 && s.Name.Length > 2; ExpressionReplaceType <Student, Teacher> replace1 = new ExpressionReplaceType <Student, Teacher>(); var newWhere1 = replace1.ReplaceBodyType(where) as Expression <Func <People, Teacher, Boolean> >; var lambda1 = newWhere1.Compile(); WriteLine(Parsing.ParsingExpression(newWhere1)); ExpressionReplaceType <People, Teacher> replace2 = new ExpressionReplaceType <People, Teacher>(); var newWhere2 = replace2.ReplaceBodyType(newWhere1) as Expression <Func <Teacher, Teacher, Boolean> >; var lambda2 = newWhere2.Compile(); WriteLine(Parsing.ParsingExpression(newWhere2)); }
private void Test1() { var ParsingExpressionTrees = new ParsingExpressionTrees(); var ParasingExpressionTreeByVisitor = new ParsingExpressionTreeByVisitor(); { ParameterExpression valueExp = Expression.Parameter(typeof(int), "Value"); //创建参数表达式 Value ParameterExpression resultExp = Expression.Parameter(typeof(int), "Result"); //创建参数表达式 Result LabelTarget lableExp = Expression.Label(typeof(int), "Break"); //创建一个标签以从循环跳转到,接收一个int类型的值 BlockExpression blockExp = Expression.Block( //创建代码块 new[] { resultExp } //定义局部变量 , Expression.Assign(resultExp, Expression.Constant(1)) //给变量赋值 , Expression.Loop( //定义循环体 Expression.IfThenElse( //创建条件表达式 if else Expression.GreaterThanOrEqual(valueExp, Expression.Constant(1)) //valueExp>=1 , Expression.MultiplyAssign(resultExp, Expression.PostDecrementAssign(valueExp)) // if true resultExp*=valueExp-- , Expression.Break(lableExp, resultExp) // if else 跳转到lableExp,并将resultExp传入到跳转到lableExp ) , lableExp // 跳转到lableExp ) ); var lambda = Expression.Lambda <Func <int, int> >(blockExp, valueExp); int value = lambda.Compile().Invoke(6); WriteLine("{0}:{1}", lambda.Body, value); WriteLine("lambda:{0}", ParsingExpressionTrees.ParsingExpression(lambda)); WriteLine("=============================================================================="); WriteLine("ParasingExpressionTreeByVisitor:"); WriteLine("{0}", ParasingExpressionTreeByVisitor.Parsing(lambda)); WriteLine("=============================================================================="); } { Expression <Func <int, int> > lambda = num => num + 100; WriteLine("lambda :{0} ", ParsingExpressionTrees.ParsingExpression(lambda)); } }