C # expression tree is constructed in one way through lambda expressions, the construction is simple expression<func<>> name=lambda;
Func<> a delegate with a return value, which the system itself contains, can be called directly. The last parameter in <> is the type of the parameter returned.
Below is my example, there is an entity class for users. Pass in a users entity that returns a bool value.
After the completion of the construction is called, the expression tree expressions The Complie () method, the result is a func<> delegate, the value of the delegate is equal to the value passed to the lambda expression.
Console.foregroundcolor = Consolecolor.green; Expressionbool0; Funcbool> func = expr.compile (); New 1 }; Console.WriteLine (Func (U). ToString ());
One of the examples below is built through the API, and we create the lambda expression above again. It is important to note that the parameters of the simultaneous we build are O. Id, the reflection is used here, first see the lambda expression as o=>o.id==0
In the parameterexpression. An o, the parameter type is users, reflecting the property ID of the users.
Expression<func<users,BOOL>>Expre; ParameterExpression par1= Expression.parameter (typeof(Users),"o"); PropertyInfo Pro=typeof(Users). GetProperty ("Id", BindingFlags.Instance |bindingflags.public); Memberexpression Mem=Expression.property (par1, Pro. Name); ConstantExpression Con= Expression.constant (0,typeof(int)); Binaryexpression bin=expression.equal (mem, con); Expre= Expression.lambda<func<users,BOOL>> (Bin,Newparameterexpression[] {par1}); BOOLA =expre.compile () (U); Console.WriteLine (A.tostring ()); Console.read ();
The result of the operation is: false false
Hey, just a simple implementation ............ Just realize, there is nothing to optimize the like ...
Come on.
More trouble slowly learn, slowly update ...
Two building----Simple examples of C # expression trees