. Net series: Expression Tree, lambda, anonymous delegate use, expressionlambda

Source: Internet
Author: User

. Net series: Expression Tree, lambda, anonymous delegate use, expressionlambda

First, define a generic delegate type as follows:

public delegate T Function<T>(T a, T b);

Implements the subject code of generic delegation and calls:

 

 

1 public static string Add (string a, string B) 2 {3 return string. format ("{0 }####{ 1}", a, B ); 4} 5 // real-name delegation mode 6 Function <string> func = new Function <string> (Add); 7 Console. writeLine (func ("hello", "world"); 8 9 // 10 functions <string> func1 = new Function <string> (delegate (string, string B) {11 return string. format ("{0 }@{ 1}", a, B); 12}); 13 Console. writeLine (func1 ("hello", "world"); 14 1 5 // Lambda expression mode 16 Function <string> func2 = (a, B) => string. format ("{0} ***** {1}", a, B); 17 Console. writeLine (func2 ("hello", "world"); 18 19 Expression <Function <string> func2_0; 20 // func2_0 = func; // The delegate cannot be directly assigned to Expression Tree 21 // func2_0 = func1; // The delegate cannot be directly assigned to Expression Tree 22 // func2_0 = func2; // The delegate cannot be directly assigned to the Expression Tree 23 24 // (a, B) => string. format ("{0} ***** {1}", a, B) the type of the statement block is lambda expression, that is, we often say lambda expression 25 // so, func2 _ 0 = (a, B) => direct assignment of string. Format ("{0} ***** {1}", a, B) is correct. 26 func2_0 = (a, B) => string. format ("{0} ***** {1}", a, B); 27 Console. writeLine (func2_0.Compile () ("hello", "world "));

 

The code above demonstrates four methods defined by the delegate type Function <T> subject, namely real-name delegation, anonymous delegation, Lambda expressions, and expression Tree.

From the Code definition of the Function <T> delegate subject, it is becoming more simple and friendly. Most of these changes are due to the syntax sugar of C.

Summary: No matter how simple the delegate entity is in writing, it still cannot change the nature of its delegate type. The delegate code block will be executed immediately when it is called.

With the development of C #, I later added expression, short for expression tree. I want to use ling to SQL, linq to entity, linq to xml, and so on.
Expression is a data structure. We can break down and store each part of the C # statement block (or expression) that is commonly written into this tree structure, statement blocks stored in the expression tree structure cannot be directly executed.
When we need to extract and restore the data in the expression structure, we need to call the expression. Compile () method, which is called compilation here. After compilation, the result is the statement block we saved previously. This is the process of restoring the idiom sentence block in the data structure (this is a metaphor ).
Of course, different output results will be generated based on different parsing engines when data is restored to idioms. If the engine is linq to SQL, the SQL output after parsing is the SQL statement that can be executed by the database, if the engine is linq to xml, the parsed output is an expression like Xpath (not verified in person)

Let me try to store and compile and output expression data with you !!!! The preceding scenario is used as an example.

1 // expression Expression Tree subject construction start 2 ParameterExpression paramA = expression. parameter (typeof (object), "a"); // declare the Parameter Expression a 3 ParameterExpression paramB = Expression in the Lambda Expression. parameter (typeof (object), "B"); // declare the Parameter Expression B 4 ConstantExpression constantExp = Expression in the Lambda Expression. constant ("{0 }!!!!! {1} ", typeof (string); // declare a text block constant Expression 5 MethodCallExpression bodyExp = Expression. call (typeof (string ). getMethod ("Format", new Type [] {typeof (string), typeof (object), typeof (object)}) 6, new Expression [] {constantExp, paramA, paramB}); // declare String. format () method call expression 7 // expression Tree subject construction end 8 9 10 // 1. construct the lambda Expression Tree of LambdaExpression type, and obtain the primitive type (weak type) of the delegate after compilation ). 11 LambdaExpression func3 = Expression. lambda (bodyExp, paramA, paramB); // combine the above expressions into the Lambda expression 12 Delegate dg = func3.Compile (); // compile the expression tree to obtain the Delegate 13 Console. writeLine (dg. dynamicInvoke ("hello", "world"); // call the delegate and output the result to the Console 14 // Console. writeLine (func3.Compile (). dynamicInvoke ("hello", "world"); // the above two steps can be simplified to this sentence code 15 16 // 2. construct a generic lambda Expression Tree of Expression <Function <string>, which can be called directly after compilation. 17 Expression <Function <string> func4 = Expression. lambda <Function <string> (bodyExp, paramA, paramB); 18 Console. writeLine (func4.Compile () ("xxxx", "yyyy"); 19 20 // 3. the construction type is Expression <Func <string, string, string> generic lambda Expression Tree, which can be called directly after compilation. 21 // The difference is that the system-defined Func <in T1, in T2, out TResult> generic delegate replaces the custom Function <T> delegate. 22 Expression <Func <string, string, string> func5 = Expression. lambda <Func <string, string, string> (bodyExp, paramA, paramB); 23 Console. writeLine (func5.Compile () ("yyyy", "zzzz"); 24 25 // The above summarizes the creation and calling methods of expression expressions, below are some examples of expression extensions 26 // 4. dynamically construct a string. concat ("hello", "world") Statement Block 27 var concatMethod = typeof (string ). getMethod ("Concat", new [] {typeof (string), typeof (string)}); 28 var addExpr = Expression. add (Expression. constant ("hello"), Expression. constant ("world"), concatMethod); 29 Expression <Func <string> e = Expression. lambda <Func <string> (addExpr); 30 Console. writeLine (e. compile (); 31 32 // 5. dynamically Construct Math. sin (100) Statement Block 33 ParameterExpression expA = Expression. parameter (typeof (double), "a"); // Parameter a34 MethodCallExpression expCall = Expression. call (35 typeof (Math ). getMethod ("Sin", new Type [] {typeof (double)}), expA); 36 LambdaExpression exp = Expression. lambda (expCall, expA); // a => Math. sin (a) 37 Console. writeLine (exp. compile (). dynamicInvoke (100); 38 39 // 6. dynamically construct the Console. writeLine ("aaa") Statement block 40 ConstantExpression _ constExp = Expression. constant ("aaa", typeof (string); // a Constant of 41 MethodCallExpression _ methodCallexp = Expression. call (typeof (Console ). getMethod ("WriteLine", new Type [] {typeof (string)}), _ constExp); 42 Expression <Action> consoleLambdaExp = Expression. lambda <Action> (_ methodCallexp); 43 consoleLambdaExp. compile ()();

 

 

 

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.