"C # Review Summary" elaborate expression tree

Source: Internet
Author: User

1Preface

Department Class 1: Commissioned

Department 2: An anonymous approach

Series 3: About lambda expressions

Series 4: Generic Delegates

Series 5: Elaborate expression tree

Series 6: Events in detail

The sound is still, the preface, followed by the big guy's article as the beginning.

The expression tree actually has nothing to do with the delegate, it has to be related, so to speak, the expression tree is the container that holds the delegate. If you want to speak more professionally, an expression tree is a data structure that accesses Lambda expressions. To use a Lambda expression, get it directly from the expression,Compile () can be used directly. The following code:

usingSystem;usingSystem.Linq.Expressions;namespaceexpressions{classProgram {Static voidMain (string[] args) {Expression<Func<int,int,int>> exp = (x, y) + x +y; Func<int,int,int> fun =Exp.compile (); intresult = Fun (2,3); Console.WriteLine ("{0}", result);                   Console.readkey (); }    }}
2What is an expression tree

The new expression treefeature in. NET 3.5 introduces the concept of "logical as data" for thefirst time in the . NET platform. That is, we can write a piece of logic in the code in the form of a high-level language, but this logic will eventually be saved as data. Because of this, we can deal with it in a variety of different ways. For example, you can turn it into a SQL Query, or an external service invocation, and so on, which is one of the Important cornerstones of the technical implementation of LINQ to everything.

Expression trees, also known as expression trees, represent the code as an object tree in an abstract way, and each node in the tree is itself an expression. An expression tree is not executable code, it is a data structure.

3use of expression trees3.1Building an expression tree

The System.Linq.Expressions namespace contains classes that represent expressions, all of which derive from expression, and we can create an instance of an expression class from a static method in those classes. The expression class consists of two important attributes:

    • The Type property represents the. NET type of the evaluation expression, which can be treated as a return type
    • The NodeType property returns the type of expression that is represented

Let's look at a simple example of building an expression tree:

Expression NumA = Expression.constant (6); Console.WriteLine ("NodeType: {0}, Type: {1}", Numa.nodetype, Numa.type); Expression NumB= Expression.constant (3); Console.WriteLine ("NodeType: {0}, Type: {1}", Numb.nodetype, Numb.type); Binaryexpression Add=Expression.add (NumA, NumB); Console.WriteLine ("NodeType: {0}, Type: {1}", Add. NodeType, Add. Type); Console.WriteLine (add); Console.read ();

As you can see from the example, we have constructed an expression tree (6+3) and looked at the type and NodeType properties of each node.

Expression has many derived classes, and there are many node types. For example, binaryexpression represents any operation with two tree of operations. This is where the NodeType attribute is important to distinguish between different kinds of expressions represented by the same class. Other node types are not covered and are interested to refer to MSDN.

For the above example, you can describe the resulting expression tree, and it is worth noting that the "leaf" expression was first created in the code, and the expression was built from the bottom up. Expressions are immutable, and all expressions can be cached and reused.

3.2 Compiling an expression into a delegate

LambdaExpression is one of the types derived from expression. The generic type expression<tdelegate> is also derived from lambdaexpress.

The difference between expression and expression<tdelegate> is that a generic class flags in a static type what kind of expression it is, that is, it determines the return type and Parameters . For example, the addition example above, the return value is an int type, no parameters, so we can use the signature func<int> to match, so we can use expression<func<int>> Represents the expression in a statically typed manner .

The purpose of this is that LambdaExpression has a compile method that can create a delegate of the appropriate type. Expression<tdelegate> also has a method with the same name, which can return a delegate of type TDelegate. Once the delegate is obtained, we can execute the expression in the same way that the normal delegate instance is called.

Following the example of addition above, we convert the above addition expression tree to a delegate and then execute the delegate:

func<int> adddelegate = expression.lambda<func<int>>(add). Compile (); Console.WriteLine (AddDelegate ());

From this example we see how to construct an expression tree and then compile the object tree into real code. The expression tree in. NET 3.5 can only be a single expression and cannot represent a complete class or method. This has been improved in. NET 4.0, where expression trees can support dynamic types, we can create blocks, assign values to expressions, and so on.

3.3 Converting a lambda expression to an expression tree

The lambda expression not only creates a delegate instance, C # 3.0 provides built-in support for converting a lambda expression into an expression tree. We can use the compiler to convert a lambda expression into an expression tree and create an instance of expression<tdelegate>.

In the following example, we convert a lambda expression into an expression tree and view the parts of the expression tree through code:

Static voidMain (string[] args) {    //To convert a lambda expression to an expression tree of type expression<t>//expression is not executable codeexpression<func<int,int,int>> expression = (A, b) = + A +b;    Console.WriteLine (expression); //get the body of a lambda expressionBinaryexpression BODY =(binaryexpression) expression.    Body; Console.WriteLine (expression.    Body); //get the parameters of a lambda expressionConsole.WriteLine ("param1: {0}, Param2: {1}", expression. parameters[0], expression. parameters[1]); ParameterExpression Left=(parameterexpression) body.    Left; ParameterExpression Right=(parameterexpression) body.    right; Console.WriteLine ("Left body of expression: {0}{4} NodeType: {1}{4} right body of expression: {2}{4} Type: {3}{4}", left. Name, body. NodeType, right. Name, body.     Type, Environment.NewLine); //converts an expression tree to a delegate and executesfunc<int,int,int> adddelegate =Expression.compile (); Console.WriteLine (AddDelegate (Ten, -)); Console.read ();}
4 Summary

As I saw earlier, we can construct an expression tree through the various node types in the derived class of expression, and then we can convert the expression tree to the appropriate instance of the delegate type, and finally execute the code of the delegate instance. However, we do not execute the code of the delegate instance around such a large bend.

Expression trees are primarily used in LINQ to SQL, and we need to convert a LINQ to SQL query expression (return IQueryable type) to an expression tree. The conversion is required because the LINQ to SQL query expression is not executed in C # code, the LINQ to SQL query expression is converted to SQL, sent over the network, and finally executed on the database server.

Reference: http://blog.jobbole.com/84588/

Recommended reading: Ascendas boss's more-and-more expression tree

"C # Review Summary" elaborate expression tree

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.