上一篇的 Hello World 简单介绍了.Net4 Expression Tree 的用法,这一篇主要介绍以下表达式——
public static ConditionalExpression IfThen(Expression test, Expression ifTrue); public static ConditionalExpression IfThenElse(Expression test, Expression ifTrue, Expression ifFalse); public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, params SwitchCase[] cases); public static SwitchCase SwitchCase(Expression body, params Expression[] testValues);
没错,都是条件语句。相信很多学编程的童鞋们学完 Hello World 以后,就会接着学if、switch 之类的语句。而表达式也同样如此。虽然形式上表达式跟编程语言有点类似,但实际使用中却没那么友好,呵呵!
IfThen
要实现的语句:
if (score < 60) { Console.WriteLine("不合格!"); }
对应的表达式:
var ifThenExpr = Expression.IfThen( Expression.LessThan(scoreExpr, Expression.Constant(60)),// score < 60 Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("不合格!") )// Console.WriteLine("不合格!"); );
IfThenElse
要实现的语句:
if (score < 60) { Console.WriteLine("不合格!"); } else { Console.WriteLine("合格!"); }
对应的表达式:
var ifThenElseExpr = Expression.IfThenElse( Expression.LessThan(scoreExpr, Expression.Constant(60)),// score < 60 Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("不合格!") ),// Console.WriteLine("不合格!"); Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("合格!") )// Console.WriteLine("合格!"); );
SwitchCase
要实现的语句:
switch (n) { case 1: Console.WriteLine("一言九鼎!"); break; case 2: Console.WriteLine("双喜临门!"); break; case 3: Console.WriteLine("三生有幸!"); break; case 4: Console.WriteLine("四海为家!"); break; default: Console.WriteLine("Unknown!"); break; }
对应的表达式:
var switchCaseExpr = Expression.Switch( //switch (n) numExpr, //default: Console.WriteLine("Unknown!?"); Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("Unknown!") ), new SwitchCase[]{ //case 1: Console.WriteLine("一言九鼎!"); Expression.SwitchCase( Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("一言九鼎!") ), Expression.Constant(1) ), //case 2: Console.WriteLine("双喜临门!"); Expression.SwitchCase( Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("双喜临门!") ), Expression.Constant(2) ), //case 3: Console.WriteLine("三生有幸!"); Expression.SwitchCase( Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("三生有幸!") ), Expression.Constant(3) ), //case 4: Console.WriteLine("四海为家!"); Expression.SwitchCase( Expression.Call( null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), Expression.Constant("四海为家!") ), Expression.Constant(4) ) } );
总结
开始两篇的介绍都是很闷的,你可以选择跳过去,不懂再跳回来,或者选择一目十行,但千万别轻言放弃。就如练武之人先练马步,练拳练腿,终将成为一代宗师,再回顾才发现一招一式离不开当初的练习。