Using system; using system. collections. generic; using system. LINQ; using system. reflection; using system. text; using system. threading. tasks; using system. LINQ. expressions; namespace testexpressionlambda {class programexpression {static void main (string [] ARGs) {expressionadd (); expressionfromlamith (); expressionstartwith (); console. read () ;}/// <summary> /// the simplest addition Expression Tree ///// root node /// banaryexpression /// Nodetype = add // type = system. int32 // The right leaf of the Left leaf /// firstarg secondarg // constantexpression // nodetype = constant // type = system. int32 type = system. int32 // value = 3 value = 2 // </Summary> Private Static void expressionadd () {// construct a constant expression 3 constantexpression firstarg = expression. constant (3); // construct a constant expression 2 constantexpression secondarg = expression. Constant (2); // build + expression 3 + 2 binaryexpression add = expression. add (firstarg, secondarg); console. writeline (ADD); // output: (3 + 2) // obtain the delegate expression <func <int> addexpression = expression. lambda <func <int> (ADD); // compile delegate, internally calls emit to construct il func <int> addfunc = addexpression. compile (); console. writeline (addfunc); // output system. func ~ 1 [int32] Console. writeline (addfunc (); // output the execution result: 5} /// <summary> /// create an Expression Tree from lambda // PS: lambda with statement blocks cannot be converted to the Expression Tree // </Summary> Private Static void expressionfromlambda () {expression <func <int> lambadexpression = () => 3 + 2; func <int> lambdafunc = lambadexpression. compile (); console. writeline (lambdafunc); console. writeline (lambdafunc ();} // <summary> // The Expression Tree calls the startwith method of the string type. // The Lambda expression of the type to be implemented: (x, y) => X. startswith (y) /// </Summary> Private Static void expressionstartwith () {// The startswith method methodinfo method = typeof (string) retrieved from the reflection string ). getmethod ("startswith", new [] {typeof (string)}); // get the parameter expression: X, Y parameterexpression x = expression. parameter (typeof (string), "x"); parameterexpression y = expression. parameter (typeof (string), "Y"); // The parameter expression [] methodargs = new [] {y} required by the startswith method }; // generate the call expression methodcallexpression call = expression. call (x, method, Y); var lambdaparameters = new [] {x, y}; // expression. lambda method generates Expression Tree delegate expression <func <string, String, bool> Lambda = expression. lambda <func <string, String, bool> (call, lambdaparameters); // compile delegate func <string, String, bool> func = lambda. compile (); console. writeline (func ("first", "second"); console. writeline (func ("first", "fir "));}}}
Basic Expression Tree Code