Expression Trees (C# and Visual Basic)

https://msdn.microsoft.com/en-us/library/bb397951.aspx

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

 

You can compile and run code represented by expression trees.

This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries.

For more information about expression trees in LINQ, see How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic).

 

Expression trees are also used in the dynamic language runtime (DLR) to provide interoperability between dynamic languages and the .NET Framework and to enable compiler writers to emit expression trees instead of Microsoft intermediate language (MSIL).

For more information about the DLR, see Dynamic Language Runtime Overview.

 

You can have the C# or Visual Basic compiler create an expression tree for you based on an anonymous匿名的 lambda expression,

or you can create expression trees manually by using the System.Linq.Expressions namespace.

 

Creating Expression Trees from Lambda Expressions

When a lambda expression is assigned to a variable of type Expression<TDelegate>, the compiler emits发出,放射;发行;发表 code to build an expression tree that represents the lambda expression.

 

The C# and Visual Basic compilers can generate expression trees only from expression lambdas (or single-line lambdas).

It cannot parse statement lambdas (or multi-line lambdas).

For more information about lambda expressions in C#, see Lambda Expressions (C# Programming Guide);

for Visual Basic, see Lambda Expressions (Visual Basic).

 

The following code examples demonstrate how to have the C# and Visual Basic compilers create an expression tree that represents the lambda expression num => num < 5 (C#) or Function(num) num < 5 (Visual Basic).

Expression<Func<int, bool>> lambda = num => num < 5;

 

posted @ 2016-03-29 11:03  ChuckLu  阅读(466)  评论(0编辑  收藏  举报