AProgramAfter retiring, the employee decided to practice calligraphy,
So I paid a lot of money to buy four treasures of wenfang.
One day, after dinner, suddenly Yaxing, some research ink paper, and a good sandalwood.
Dingshen for a moment, smack,
Solemnly write down a line: Hello world!
Recall the first line written when I studied. Net in collegeCodeYes:
Console. Writeline ("Hello world! ");
Similarly, as an example of getting started with the. net4 Expression Tree, I think the classic "Hello World" should be the most appropriate.
To better demonstrate the new function of the. net4 Expression Tree, modify the Hello world code:
StringS; S ="Hello world! ";Console. Writeline (s );
Then, use an expression to implement the preceding three statements one by one.
1. String S;
VaRS =Expression. Variable (Typeof(String),"S");
Expression. Variable: declare a variable. The first parameter specifies the type, and the second parameter specifies the name (optional ).
2. S = "Hello World ";
VaRAssignexpression =Expression. Assign (S,Expression. Constant ("Hello world! "));
Expression. Assign: assign values to S
3. Console. writeline (s );
VaRCallexpression =Expression. Call (Null,Typeof(Console). Getmethod ("Writeline",New[] {Typeof(Object)}),// Console. writeline (s );S );
Expression. Call: CallConsole. Writeline Method
Finally, you mustExpression. Block organizes the above three expressions:
Expression. Block (New[] {S}, assignexpression, callexpression)
Below isExpressionOne function signature of. Block:
Public staticBlockexpressionBlock (Ienumerable<Parameterexpression> Variables,ParamsExpression[] Expressions );
The first parameter is the specified variable (such as the example s), and the second parameter is the specific implementation expression (such as the value assignment, loop, and so on ).
Complete code:
VaR S = Expression . Variable ( Typeof ( String ), "S" ); // String S; VaR Assignexpression = Expression . Assign (S, Expression . Constant ( "Hello world! " )); // S = "Hello world! " VaR Callexpression = Expression . Call ( Null , Typeof ( Console ). Getmethod ( "Writeline" , New [] { Typeof ( Object )}), // Console. writeline (s ); S ); VaR Writelineexpression = Expression . Lambda < Action > ( Expression . Block ( New [] {S}, assignexpression, callexpression )); VaR Writeline = writelineexpression. Compile (); writeline ();
Summary
Hello, Expression Tree!