Lambda中Func和Expression的区别

Lambda中Func和Expression的区别

 

 

[csharp] view plain copy
 
  1. <span style="white-space:pre">    </span>static void TestExpression()  
  2.         {  
  3.             Func<int> Func = () => 10;  
  4.             Expression<Func<int>> Expression = () => 10;  
  5.   
  6.             Func<int, bool> f = i => i == 10;  
  7.             Expression<Func<int, bool>> e = x => x == 10;  
  8.   
  9.   
  10.             //Func<TObject, bool> 是委托(delegate)  
  11.             //Expression < Func < TObject, bool >> 是表达式  
  12.             //Expression编译后就会变成delegate,才能运行。比如  
  13.             Expression<Func<int, bool>> ex = x => x < 10;  
  14.             Func<int, bool> func = ex.Compile();  
  15.             //然后你就可以调用func:  
  16.             func(5); //-返回 true  
  17.             func(20); //- 返回 false  
  18.             System.Console.WriteLine("func(5){0}", func(5));  
  19.             System.Console.WriteLine("func(20){0}", func(20));  
  20.   
  21.             Func<int, bool> ff = i => i > 5;  
  22.             System.Console.WriteLine("ff(2){0}", ff(2));  
  23.             System.Console.WriteLine("ff(7){0}", ff(7));  
  24.   
  25.         }  



 

 

[csharp] view plain copy
 
    1. <span style="white-space:pre">    </span>static void TestExpression2()  
    2.         {  
    3.             Func<int> Func = () => 10;  
    4.             Expression<Func<int>> Expression = () => 10;  
    5.   
    6.             Func<int, bool> f = i => i == 10;  
    7.             Expression<Func<int, bool>> e = x => x == 10;  
    8.   
    9.             System.Console.WriteLine(Func);         //System.Func`1[System.Int32]  
    10.             System.Console.WriteLine(Func());       //10  
    11.             System.Console.WriteLine(f(5));         //false  
    12.             System.Console.WriteLine(f(10));        //true  
    13.   
    14.             System.Console.WriteLine(Expression);           //() => 10;  
    15.             System.Console.WriteLine(Expression.Compile()); //System.Func`1[System.Int32]  
    16.   
    17.             System.Console.WriteLine(e);            //x => (x == 10)  
    18.             System.Console.WriteLine(e.Compile());  //System.Func`2[System.Int32,System.Boolean]  
    19.   
    20.             Func<int, bool> ff = e.Compile();  
    21.             System.Console.WriteLine(ff);            //System.Func`2[System.Int32,System.Boolean]  
    22.             System.Console.WriteLine(ff(5));         //false  
    23.             System.Console.WriteLine(ff(10));        //true  
    24.   
    25.   
    26.   
    27.             Func<int> fff = Expression.Compile();  
    28.             System.Console.WriteLine(fff);      //System.Func`1[System.Int32]  
    29.             System.Console.WriteLine(fff());    //10  
    30.         }  
posted @ 2018-03-16 15:31  net5x  阅读(107)  评论(0)    收藏  举报