c#编程指南(二) LINQ表达式 (LINQ Expression)

C# 3.0 带来了强大的基于方法的查询LINQ。为了开发者更好更方便的使用LINQ,微软有随即引入两个新特性:

Lambda和Expression。Lambda简单来说就是一个匿名方法的简略写法,Expression和Lambda的关系可以从

下面的一小段代码看下:(.NET Framework 3.5, 记住引用命名空间System.Linq.Expressions;)

 

 
  
1 // simple express: 2 + 3
2   Expression e = Expression.Add(Expression.Constant( 2 ), Expression.Constant( 3 ));
3 // lambda express: () => 2 + 3;
4   LambdaExpression l = Expression.Lambda(e, null );
5 // compile to delegate.
6   Delegate d = l.Compile();
7 // convert to
8   Func < int > f = (Func < int > )d;
9 //
10  
11 Console.WriteLine(e);
12 Console.WriteLine(l);
13 Console.WriteLine(d);
14 Console.WriteLine(f());

 

输出结果为下:

 

 
  
1 ( 2 + 3 )
2 () => ( 2 + 3 )
3 System.Func` 1 [System.Int32]
4   5

 

 

 

第一个就是构造了一个简单的常数相加表达式,

第二个使用lambda形式表达。

第三个系统把lambda表达式编译成一个委托,注意这个委托是一个泛型委托形式。

第四个使用委托调用函数,输出结果 2 + 3 = 5,是不是很简单啊。

 

 

下面来一个从上面稍微改进,带参数的LINQ表达式:

 
  
1 ParameterExpression p = Expression.Parameter( typeof ( int ), " x " );
2 // expression: x + 3
3   Expression e2 = Expression.Add(p, Expression.Constant( 3 ));
4 // Lambda: x => x + 3;
5   LambdaExpression l2 = Expression.Lambda(e2, new ParameterExpression[] { p });
6 Delegate d2 = l2.Compile();
7 Func < int , int > f2 = (Func < int , int > )d2;
8
9 Console.WriteLine(e2);
10 Console.WriteLine(l2);
11 Console.WriteLine(d2);
12 Console.WriteLine(f2( 3 ));

 

这个只是多使用了一个ParameterExpression,就是声明了一个参数。第一个例子是无参函数,那么这个就是简单的带一个参数的表达式。结果如下:

 
  
(x + 3 )
x
=> (x + 3 )
System.Func`
2 [System.Int32,System.Int32]
6

 

很简单吧。

示例代码:下载

 

 

转载于:https://www.cnblogs.com/namek/archive/2010/08/14/1799418.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值