标签:
文章地址: http://www.cnblogs.com/Ninputer/archive/2009/08/28/expression_tree1.html
//定义一个表达式 ConstantExpression exp1 = Expression.Constant(1); ConstantExpression exp2 = Expression.Constant(2); BinaryExpression exp12 = Expression.Add(exp1, exp2); ConstantExpression exp3 = Expression.Constant(3); BinaryExpression exp123 = Expression.Add(exp12, exp3); //需要转为LambdaExpression 后,才能执行 LambdaExpression lambda = Expression.Lambda(exp123); Delegate func = lambda.Compile(); MessageBox.Show( func.DynamicInvoke(null).ToString()); //直接定义LambdaExpression ParameterExpression expA=Expression.Parameter(typeof(double),"a"); MethodCallExpression expCall = Expression.Call(null, typeof(Math).GetMethod("Sin"), expA); lambda = Expression.Lambda(expCall, expA); //这个是表达式字面量,自动从语言层面的表达式转为表达式树。 这个特殊语法只适于Lambda表达式。是一种语法糖! Expression<Func<double, double>> exp = a => Math.Sin(a);
表达式树最终是一个内存中树状结构的数据。可以文本化,序列化、转存、传输等等。
运行时分析表达式的逻辑
序列化或者传输表达式
重新编译成可执行的代码
课后习题:
//表达式求值时,验证表达式是否正确 LambdaExpression lambda = Expression.Lambda(expN, expA);//后面各题的表达式及参数传入此, Delegate func = lambda.Compile(); MessageBox.Show(func.DynamicInvoke(10).ToString()); //调用时,注意参数要按顺序传入 //1、 -a ParameterExpression expA = Expression.Parameter(typeof(double), "a"); UnaryExpression expN = Expression.Negate(expA); //2、a+b*2 ParameterExpression expA = Expression.Parameter(typeof(double), "a"); ParameterExpression expB = Expression.Parameter(typeof(double), "b"); ConstantExpression exp2=Expression.Constant(2.0); BinaryExpression expb2 = Expression.Multiply(exp2, expB); BinaryExpression expab2 = Expression.Add(expA, expb2); //3、Math.Sin(x)+Math.Cos(y) ParameterExpression expx = Expression.Parameter(typeof(double), "x"); ParameterExpression expy = Expression.Parameter(typeof(double), "y"); MethodCallExpression expsin = Expression.Call(null, typeof(Math).GetMethod("Sin"), expx); MethodCallExpression expcos = Expression.Call(null, typeof(Math).GetMethod("Cos"), expy); BinaryExpression expAdd = Expression.Add(expsin, expcos); //4、new StringBuilder("hello") ConstantExpression exphello = Expression.Constant("hello"); NewExpression expNew = Expression.New(typeof(StringBuilder).GetConstructor(new Type[] { typeof(string) }), exphello);
标签:
原文地址:http://my.oschina.net/u/1540190/blog/475103