首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

c# - expression tree and lambda - serie 一

2012-12-22 
c# - expression tree and lambda - serie 1In this post, we are going to discuss the topic on the Exp

c# - expression tree and lambda - serie 1

In this post, we are going to discuss the topic on the Expression Tree and Delegate and Lambda, we are going to go through from simple expresison, then expression converted to delegate (lambda), and then we shape up/build up to a more complicated Expression Tree example and we compare it with its equivalent Lambda expression, later we shows why behind Expression Tree since we have the lambda expresion which has hte nice compile time check.

Code as Data

Code as Data is a long existed idea. But it hasn't bee used much in popular programming language. Expression Tree in .NET provides an abstract way of representing the code as a tree of objects. It's like COdeDOM but operate at a slightly higher level. The primary use of Expression tree is in LINQ and you can custom Expression to enable code execution in another end (or even language)

?

Expression Trees

The namespace in question is "System.Linq.Expression" , of all the classes that is contained in this namespace, Expression is the one that you may use most.?

?

Build a ?simple expression tree

Let's first see an simple example of Building a exprssion tree

?

?

In the Expression class, there are two properties?

Type: the .NET type of the evaluated Expression

NodeType: returns the kind of expression represented , as a member of ExpressoinType enumeration,with values such as LessThan....


?As you already know, we have build the ExpressionTree, but we can do barely anything with it, except, Expression has a Compile method which will turnst the Tree representaion of the expresion into executable code piece - a delegate. ?Below shows how.

?

?

?

HINT, you can visualize the Expression Tree from the Text Visualizer.?

?

Expression Tree at the heart of LINQ.

Without lambda expresison, Expression Tree would have little value. They'd be an alternative to CodeDOM.

?

It is also ture for the reverse to a limited extent: without expression trees, lambda expression would certainmly be less useful. HAVing a more compact way of creating delegate would be welcome, and hte shift towards a more functinal development model would still be viable. Lambda expression are particular effective when combined with extension methods. But with expresion tree in the picture as well, things get a lot more interesting.?

?

Lambda expression provide:

Compile-check

Expression Tree provides:

abstract the execution model away from the desired logic.?

?

LINQ to SQL is good example of combination of Lamdba Expression and Expression Tree.


c# - expression tree and lambda - serie 一

?

热点排行