(i) lambda create an expression tree
Expression<func<int, int, int>> EXP1 = (A, b) => A * b+2;
Explain: Func
func< (Of < (T1, T2, tresult>) >)
Generic delegate: Encapsulates a method that has two parameters and returns the type value specified by the TResult parameter.
T1: The first parameter type of the method that this delegate encapsulates.
T2: The second parameter type of the method that this delegate encapsulates.
Tresult: The return value type of the method that this delegate encapsulates.
For example: now for the 2 int type and (1) The original method
public int Add (int a, int b)
{return
a + b;
}
(2) through the delegate to achieve
delegate int Deleadd (int a, int b);
public void Deleconcrete ()
{
deleadd deleadd= Add;
Deleadd (1, 2);
}
(3) directly through the generic delegate func to achieve
public int Getfunc (int a,int b)
{
func<int, int, int> add = add;
Return Add (A, b);
(ii) Decomposition of the expression directory tree
This may think of arithmetic in elementary school mathematics. For a*b+2, first multiply, then add
Represented by a figure:
each rectangle is a node (the type of expression), and there are several types of nodes.
And this (a+b) *2 several nodes: a,b is a parameter, the type is ParameterExpression +,*, is a two-dollar character, the type is Binaryexpression 2 constant, the type is ConstantExpression (iii) Creation of a tree by expression type
The a*b+2 node has 4, 2 parameters, 2 operators, 1 constants
Two parameters
ParameterExpression a = Expression.parameter (typeof (int), "a");
ParameterExpression B = Expression.parameter (typeof (int), "B");
Quadrature
binaryexpression multi=expression.multiply (a,b);
Constant
constantexpression x2 = expression.constant (2);
Sum
binaryexpression Add = Expression.add (Multi, x2);
Creates an object that represents a Lambda expression
lambdaexpression lexp = expression.lambda<func<int, int, int>> (ADD, A, b);
View an expression
Console.WriteLine (Lexp. ToString ());
The creation method is created by the expression factory method. (iv) Use
Expression<func<int, int, int>> lexp = expression.lambda<func<int, int, int>> (ADD, A, b);
Func<int, int, int> fun = Lexp.compile ();
Console.WriteLine (Fun (3,5));