Lambda中Func和Expression的区别
<span style="white-space:pre"> </span>static void TestExpression()
{
Func<int> Func = () => 10;
Expression<Func<int>> Expression = () => 10;
Func<int, bool> f = i => i == 10;
Expression<Func<int, bool>> e = x => x == 10;
//Func<TObject, bool> 是委托(delegate)
//Expression < Func < TObject, bool >> 是表达式
//Expression编译后就会变成delegate,才能运行。比如
Expression<Func<int, bool>> ex = x => x < 10;
Func<int, bool> func = ex.Compile();
//然后你就可以调用func:
func(5); //-返回 true
func(20); //- 返回 false
System.Console.WriteLine("func(5){0}", func(5));
System.Console.WriteLine("func(20){0}", func(20));
Func<int, bool> ff = i => i > 5;
System.Console.WriteLine("ff(2){0}", ff(2));
System.Console.WriteLine("ff(7){0}", ff(7));
}
<span style="white-space:pre"> </span>static void TestExpression2()
{
Func<int> Func = () => 10;
Expression<Func<int>> Expression = () => 10;
Func<int, bool> f = i => i == 10;
Expression<Func<int, bool>> e = x => x == 10;
System.Console.WriteLine(Func); //System.Func`1[System.Int32]
System.Console.WriteLine(Func()); //10
System.Console.WriteLine(f(5)); //false
System.Console.WriteLine(f(10)); //true
System.Console.WriteLine(Expression); //() => 10;
System.Console.WriteLine(Expression.Compile()); //System.Func`1[System.Int32]
System.Console.WriteLine(e); //x => (x == 10)
System.Console.WriteLine(e.Compile()); //System.Func`2[System.Int32,System.Boolean]
Func<int, bool> ff = e.Compile();
System.Console.WriteLine(ff); //System.Func`2[System.Int32,System.Boolean]
System.Console.WriteLine(ff(5)); //false
System.Console.WriteLine(ff(10)); //true
Func<int> fff = Expression.Compile();
System.Console.WriteLine(fff); //System.Func`1[System.Int32]
System.Console.WriteLine(fff()); //10
}
版权所有,转载请注明文章出处 http://blog/csdn.net/cadenzasolo