Getting started with Expression Tree

Source: Internet
Author: User

The Expression Tree is provided in. NET Framework 3.5. It is an abstract syntax tree or a data structure. Before learning about him, we need to start with the Commission,
In. net, the delegate is to useDelegateA reference type declared by the keyword, similar to the function pointer in C ++. You can regard the delegate as the alias of the method, but it represents a class of method.
Delegation is safe and reliable.

1. Let's take an example to briefly describe the use of delegation. Suppose we have a staff organization library, and we want to list the names of all the staff in the warehouse. The following code is used:

public class Employe    {        public string Name { get; set; }        public int Age { get; set; }        public Employe(string name,int age)        {            this.Name = name;            this.Age = age;        }    }
public delegate void ProcessEmployeDelegate(Employe emp);    public class EmpDataBase{        List<Employe> list = new List<Employe>         {            new Employe("Cary",25),            new Employe("James",34)        };                public void ProcessEmploye(ProcessEmployeDelegate processEmploye)        {            foreach (Employe emp in list)            {                processEmploye(emp);            }        }}

Class program {static void showempname (employe EMP) {"Name: {0 }". formatwriteline (EMP. name);} static void main () {empdatabase empdb = new empdatabase (); empdb. processemploye (showempname );
}

}

The result is as follows:

Name: Cary
Name: James

I added a simple extension method for string. The Code is as follows:

public static void FormatWriteLine(this string format, params object[] args){     Console.WriteLine(string.Format(format, args));}
2. In the era of. net2.0, an anonymous method was introduced. Using an anonymous method, we don't have to create a separate method, but passed the anonymous method directly as a parameter. The above main program can be changed to the following code:
Class program {static void main () {empdatabase empdb = new empdatabase (); empdb. processemploye (delegate (employe EMP) {"Name: {0 }". formatwriteline (EMP. name );});
}
}
3. When we enter the. net3.x era, we have lambda expressions which can also remove the delegate keyword, so that the delegate shadow is completely invisible. The Code is as follows:
Class program {static void main () {empdatabase empdb = new empdatabase (); empdb. processemploye (EMP => "Name: {0}". formatwriteline (EMP. Name ));
}
}
4. So far, our main program has been much simplified. However, we also declare a processemployedelegate delegate, which can be replaced by action or func. Action
There is no difference between the functions of func <t, tresult>, but action <t> does not return type. The Code is as follows:
public void ProcessEmploye(Action<Employe> processEmploye){      foreach (Employe emp in list)      {           processEmploye(emp);      }}

5. After learning about lambda expressions, the specific syntax tree is Expression Tree. The corresponding APIs are all in the system. LINQ. Expressions namespace, for example:

Let's take a look at the structure of the expression class, which has four attributes:

Body: obtains the body of an expression;
Parameters: Get the lambda expression parameters;
Nodetype: Get the expression type (expressiontype) of some nodes in the tree. This is an enumeration type with 45 different values, representing all possible types of expression nodes, such as returning constants,
It may also return parameters, whether a value is smaller than another (<), whether a value is greater than another (>), or two values and.
Type: Obtain the static type of the expression. In this example, the expression type is func.

6. We can build, traverse, modify the expression directory tree, and execute the expression directory tree. The following describes several examples. Find the employees whose strings start with "C" (x => X. startswith ("C ")):

String[] names = new string[2] { "Cary","James"};Expression<Func<String, Boolean>>  expression1 = (x) => x.StartsWith("C");"Expression is {0}\r\n".FormatWriteLine(expression1.ToString());          foreach (String name in  names.Where(expression1.Compile())){            "{0 }".FormatWriteLine(name);}

7. Find the employee whose age is 25 in the staff library, and the expression is: expression is age => (age. Age = 25)

ConstantExpression constEmpAge = Expression.Constant(25);ParameterExpression paramAge =Expression.Parameter(typeof(Employe), "age");MemberExpression mex =LambdaExpression.PropertyOrField(paramAge, "Age");BinaryExpression filter = Expression.Equal(mex, constEmpAge);Expression<Func<Employe, bool>> expression2 = Expression.Lambda<Func<Employe, bool>>  (filter,new ParameterExpression[] { paramAge });            "Expression is {0}\r\n".FormatWriteLine(expression2.ToString());foreach (Employe emp in list.Where(expression2.Compile())){      "{0}:{1}".FormatWriteLine(emp.Name,emp.Age);}

8. We can also use Expression Tree Visualizer to view information about the expression directory tree, such:

Use Expression Tree Visualizer to copy the. dll file in expressiontreevisualizer to .. \ Program Files \ Microsoft Visual Studio 9.0 \ common7 \ packages \ debugger \ visualizers.

This article does not have much in-depth content. I just hope to give you some basic understanding of expression and hope this article will be useful to you.

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.