// Lambda expression as executable code. Func < int , bool > deleg = i => i < 5 ; // Invoke the delegate and display the output. Console.WriteLine( " deleg(4) = {0} " , deleg( 4 )); // Lambda expression as data in the form of an expression tree. System.Linq.Expressions.Expression < Func < int , bool >> expr = i => i < 5 ; // Compile the expression tree into executable code. Func < int , bool > deleg2 = expr.Compile(); // Invoke the method and print the output. Console.WriteLine( " deleg2(4) = {0} " , deleg2( 4 )); /**/ /* This code produces the following output: deleg(4) = True deleg2(4) = True*/
(2)Expression(TDelegate).Compile Method 编译lambda expression按照表达式树描述执行代码. public TDelegate Compile() 返回值是TDelegate类型. 一个TDelegate类型的委托表示lambda expression按照Expression(TDelegate)描述. 注意: 在运行时编译方法产生一个TDelegate 类型的委托.当这个委托被执行的,它的行为按照Expression(TDelegate)语意来描述. 编译方法能被使用来获得任何表达式树的值.首先创建一个已经有使用Lambda方法的表达式的主体的lambda expression.之后调用编译获得委托,并且执行委托获得expression式的值. // Lambda expression as data in the form of an expression tree. System.Linq.Expressions.Expression < Func < int , bool >> expr = i => i < 5 ; // Compile the expression tree into executable code. Func < int , bool > deleg = expr.Compile(); // Invoke the method and print the output. Console.WriteLine( " deleg(4) = {0} " , deleg( 4 )); /**/ /* This code produces the following output: deleg(4) = True*/