. NET series: expression tree, lambda, anonymous delegate use "Go"

Source: Internet
Author: User
Tags sin

Https://www.cnblogs.com/nicholashjh/p/7928205.html

First define a generic delegate type, as follows:

Public delegate T Function<t> (t A, t B);

Implement the principal code for the generic delegate, and invoke:

1PublicStaticString Add (String A,Stringb2{3ReturnString. Format ("{0} # # # # 1}", A, b);4}5//Real name Entrustment method6 function<string> func =New function<String>(ADD);7 Console.WriteLine (Func ("Hello","World") );89//Anonymous delegate modeTen function<String> func1 =New function<String> (DelegateString A,Stringb) {11ReturnString. Format ("{0} {1", A, b);12});Console.WriteLine (Func1 ("Hello","World"));1415//Lambda expression stylefunction<String> Func2 = (A, b) = =String. Format ("{0} * * * * {1}", A, b);Console.WriteLine (Func2 ("Hello","World"));18expression<function<String>>Func2_0;20//Func2_0 = func;//Assigning a delegate directly to an expression tree is not supported21st//Func2_0 = func1;//Assigning a delegate directly to an expression tree is not supported22//Func2_0 = Func2;//Assigning a delegate directly to an expression tree is not supported2324 // (A, b) = = string . The type of Format ("{0} * * * * {1}", A, b) statement block is lambda expression, which we often say lambda expressions 25 // so, Func2_0 = (A, b) = = string. There is no problem with the direct assignment of Format ("{0} * * * * {1}", A, b). 26 func2_0 = (A, b) = string. Format ( "{0} * * * 1}" Span style= "color: #000000;" >, a, b); 27 Console.WriteLine (Func2_0.compile () ( "hello" world")); 

The above code shows the four ways in which the delegate type function<t> the body definition, namely the real name delegate, anonymous delegate, lambda expression, expression tree.

From the code definition of the function<t> principal, it is increasingly simple and friendly, and much of this change is due to C # 's syntactic sugars.

Summary: No matter how the principal of the principal is simplified in the form of writing, it still cannot change the nature of its delegate type, and executes immediately when the delegate code block is called.

With the development of C #, and later added to the expression of this east, short, I want to use Ling to SQL, LINQ to Entity, LINQ to XML and so on you are not unfamiliar.
expression is a data structure in which we can decompose the parts of a common C # statement block (or expression) into the tree structure, and the block of statements stored in the expression tree structure cannot be executed directly.
We need to call the Expression.compile () method when we need to extract and restore the data in the expression structure, which I call compiling. The result of the compilation is the block of statements we previously deposited, which is the process of restoring a data structure to a block of statements (this is a metaphor).
Of course, when you restore data to a statement block, depending on the parsing engine, different output results will be produced, if the Engine is LINQ to SQL then the output is the SQL that is available to the database execution, if the engine is LINQ to XML parsing output is an expression such as XPath (not personally verified)

I want you to come with me. To experience the storage and compilation output of expression data!!! Still taking the above scenario as an example

1//Expression Tree Body Construction begins2 ParameterExpression Parama = Expression.parameter (typeofObject),"A");//Declaring a parameter expression in a lambda expression3 ParameterExpression paramb = Expression.parameter (typeofObject),"B");//Declaring a parameter expression in a lambda expression b4 ConstantExpression constantexp = Expression.constant ("{0}!!!!! {1}",typeofstring));//Declaring a text block constant expression5 Methodcallexpression bodyexp = Expression.call (typeofString). GetMethod ("Format",New type[] {typeofString),typeofObject),typeofObject) })6,New expression[] {constantexp, Parama, paramb});//Declaring an String.Format () method call expression7//Expression Tree Body construction end8910//1. Constructs a lambda expression tree of type lambdaexpression, which gets the primitive type (weak type) of the delegate after compilation.One lambdaexpression func3 = Expression.lambda (Bodyexp, Parama, paramb);//Combine each of these expression parts into a lambda expressionDelegate dg = Func3.compile ();//Compiling an expression tree to get a delegateConsole.WriteLine (DG. DynamicInvoke ("Hello","World"));//Invoking a delegate and outputting the result to the console14//Console.WriteLine (Func3.compile (). DynamicInvoke ("Hello", "World");//The above two steps can be simplified as this Code1516//2. Construct a generic lambda expression tree of type expression<function<string>> that can be called directly by the delegate after compilation.expression<function<string>> Func4 = expression.lambda<function<String>>(Bodyexp, Parama, paramb);Console.WriteLine (Func4.compile () ("Xxxx","yyyy"));1920//3. Constructs a generic lambda expression tree of type expression<func<string, String, string>>, which can be called directly after compilation.21st//The difference with the above is that the custom function<t> delegate is replaced with a system-defined func<in T1, in T2, an out tresult> generic delegate.expression<func<StringStringstring>> Func5 = expression.lambda<func<StringStringString>>(Bodyexp, Parama, paramb);Console.WriteLine (Func5.compile () ("yyyy","Zzzz"));2425//The above summarizes the different ways to create and invoke expression expressions, and here are a few examples of extensions26//4. Dynamically constructs a string. Concat ("Hello", "world") statement block27var Concatmethod =typeofString). GetMethod ("Concat",New[] {typeofString),typeofString) });28var addexpr = Expression.add (Expression.constant ("Hello"), Expression.constant ("World"), Concatmethod);expression<func<String>> e = expression.lambda<func<String>>(addexpr);30Console.WriteLine (E.compile ());3132//5. Dynamically constructed Math.sin (100) statement blockParameterExpression ExpA = Expression.parameter (typeofDouble),"A");//Parameter AMethodcallexpression Expcall =Expression.call (35typeof (Math). GetMethod ("Sin",New type[]{typeofDouble)}), ExpA);LambdaExpression exp = Expression.lambda (Expcall, ExpA);//A = Math.sin (a)Panax Notoginseng Console.WriteLine (Exp.compile (). DynamicInvoke (100) );3839//6. Dynamically constructed Console.WriteLine ("AAA") statement blockConstantExpression _constexp = Expression.constant ("aaa", typeof (string));  a constant of methodcallexpression _methodcallexp = Expression.call (typeof (Console). GetMethod ("WriteLine", new type[] { typeof (string)}), _constexp);  expression<action> consolelambdaexp = expression.lambda<action> (_methodcallexp); 43 Consolelambdaexp.compile () ();                

. NET series: expression tree, lambda, anonymous delegate use "Go"

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.