Expression tree is a data structure definition code. They code for analyzing the same and generating an output compiled configuration based compiler.
Several common expression
BinaryExpression expression binary operator comprising
1 BinaryExpression binaryExpression = Expression.MakeBinary(ExpressionType.Add,Expression.Constant(1),Expression.Constant(2)); 2 Console.WriteLine(binaryExpression.ToString());//(1+2) 不进行溢出检查 3 binaryExpression = Expression.MakeBinary(ExpressionType.AddChecked, Expression.Constant(3), Expression.Constant(4)); 4 Console.WriteLine(binaryExpression.ToString());//(3+4) 进行溢出检查 5 binaryExpression = Expression.MakeBinary(ExpressionType.Subtract, Expression.Constant(5), Expression.Constant(6)); 6 Console.WriteLine(binaryExpression.ToString());//(5-6) 不进行溢出检查 7 binaryExpression = Expression.MakeBinary(ExpressionType.SubtractChecked, Expression.Constant(7), Expression.Constant(8)); 8 Console.WriteLine(binaryExpression.ToString());//(7-8) 进行溢出检查 9 binaryExpression = Expression.MakeBinary(ExpressionType.Multiply, Expression.Constant(9), Expression.Constant(10)); 10 Console.WriteLine(binaryExpression.ToString());//(9*10) 不进行溢出检查 11 binaryExpression = Expression.MakeBinary(ExpressionType.MultiplyChecked, Expression.Constant(11), Expression.Constant(12)); 12 Console.WriteLine(binaryExpression.ToString());//(11*12) 进行溢出检查 13 binaryExpression = Expression.MakeBinary(ExpressionType.Divide, Expression.Constant(13), Expression.Constant(14)); 14 Console.WriteLine(binaryExpression.ToString());//(13/14) 15 binaryExpression = Expression.MakeBinary(ExpressionType.Modulo, Expression.Constant(15), Expression.Constant(16)); 16 Console.WriteLine(binaryExpression.ToString());//(15%16)
BlockExpression block comprising a sequence of expressions, the expressions defined variables
1 BlockExpression blockExpr = Expression.Block( 2 Expression.Call(null, typeof(Console).GetMethod("Write", new Type[] { typeof(String) }), Expression.Constant("Hello ")), 3 Expression.Call(null, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }), Expression.Constant("World!")), 4 Expression.Constant(42) 5 ); 6 var result = Expression.Lambda<Func<int>>(blockExpr).Compile()(); 7 Console.WriteLine("**************************"); 8 foreach (var expr in blockExpr.Expressions) 9 Console.WriteLine(expr.ToString()); 10 Console.WriteLine("**************************"); 11 Console.WriteLine(result);
Program execution results
ConditionalExpression having expression of the conditional operator
Expression conditionExpr = Expression.Condition(Expression.Constant(num > 10),Expression.Constant("num is greater than 10"),Expression.Constant("num is smaller than 10"));
Expressions having a constant value ConstantExpression
1 Expression.Constant(5.5); 2 Expression.Constant("Hello World!");
The default value DefaultExpression type or empty expression
1 Expression defaultExpr = Expression.Default(typeof(byte)); 2 3 // Print out the expression. 4 Console.WriteLine(defaultExpr.ToString());// 等价于 default(byte) 5 6 // The following statement first creates an expression tree, 7 // then compiles it, and then executes it. 8 Console.WriteLine(Expression.Lambda<Func<byte>>(defaultExpr).Compile()());//0
ParameterExpression named parameter expression
ParameterExpression param = Expression.Parameter(typeof(int));
IndexExpression indexed or array of attributes
1 ParameterExpression arrayExpr = Expression.Parameter(typeof(int[]), "Array"); 2 ParameterExpression indexExpr = Expression.Parameter(typeof(int), "Index"); 3 ParameterExpression valueExpr = Expression.Parameter(typeof(int), "Value"); 4 Expression arrayAccessExpr = Expression.ArrayAccess( 5 arrayExpr, 6 indexExpr 7 );//Array[Index]
InvocationExpression the delegate or lambda expression to the list of expressions parameter expressions
1 Expression<Func<int, int, bool>> largeSumTest =(num1, num2) => (num1 + num2) > 1000; 2 InvocationExpression invocationExpression =Expression.Invoke(largeSumTest,Expression.Constant(539),Expression.Constant(281)); 3 Console.WriteLine(invocationExpression.ToString());//Invoke((num1, num2) => ((num1 + num2) > 1000), 539, 281)
LambdaExpression describe a lambda expression. This will capture and .NET similar method body code block
1 ParameterExpression paramExpr = Expression.Parameter(typeof(int), "arg"); 2 LambdaExpression lambdaExpr = Expression.Lambda(Expression.Add(paramExpr,Expression.Constant(1)),new List<ParameterExpression>() { paramExpr }); 3 Console.WriteLine(lambdaExpr);// arg => (arg +1)
ElementInit the initial value of the single element of the set of setting items IEnumerable
ListInitExpression represents constructor contains a collection initializer call
NewExpression constructor calls
1 string tree1 = "maple"; 2 string tree2 = "oak"; 3 4 MethodInfo addMethod = typeof(Dictionary<int, string>).GetMethod("Add"); 5 6 // Create two ElementInit objects that represent the 7 // two key-value pairs to add to the Dictionary. 8 ElementInit elementInit1 =Expression.ElementInit(addMethod,Expression.Constant(tree1.Length),Expression.Constant(tree1)); 9 ElementInit elementInit2 =Expression.ElementInit(addMethod,Expression.Constant(tree2.Length),Expression.Constant(tree2)); 10 11 // Create a NewExpression that represents constructing 12 // a new instance of Dictionary<int, string>. 13 NewExpression newDictionaryExpression = Expression.New(typeof(Dictionary<int, string>));//等价 new Dictionary<int, string>(); 14 15 // Create a ListInitExpression that represents initializing 16 // a new Dictionary<> instance with two key-value pairs. 17 ListInitExpression listInitExpression = Expression.ListInit(newDictionaryExpression, elementInit1, elementInit2);//等价 var dic= new Dictionary<int, string>{}; dic.Add(5,"maple");dic.Add(3,"oak"); 18 19 Console.WriteLine(listInitExpression.ToString());
LoopExpression infinite loop. You can use "break" to exit it
LabelTarget represent GotoExpression goal
1 ParameterExpression value = Expression.Parameter(typeof(int), "value"); 2 ParameterExpression result = Expression.Parameter(typeof(int), "result"); 3 LabelTarget label = Expression.Label(typeof(int)); 4 BlockExpression block = Expression.Block( 5 new[] { result }, 6 Expression.Assign(result, Expression.Constant(1)), 7 Expression.Loop( 8 Expression.IfThenElse( 9 Expression.GreaterThan(value, Expression.Constant(1)), 10 Expression.MultiplyAssign(result, 11 Expression.PostDecrementAssign(value)), 12 Expression.Break(label, result) 13 ), 14 label 15 ) 16 ); 17 //var s =value=> 18 //{ 19 // var result = 1; 20 // for (int i = value; i >1; i--) 21 // { 22 // result *= i; 23 // } 24 // return result; 25 //};
MemberAssignment assignment operator for the field or property of an object
MemberBinding provide a base class, the base class represent classes binding, these bindings are used to initialize the newly created object members
MemberExpression field or property access
MemberInitExpression call the constructor and initialize a new object of one or more members
The newly created object initialization element ensemble members MemberListBinding
Members of the newly created object initialization members MemberMemberBinding
. 1 public class the BaseEntity 2 { . 3 /// <Summary> . 4 /// Created account . 5 /// </ Summary> . 6 [the DataMember] . 7 [Display (the Name = " Created account " )] . 8 [the Column] . 9 public String CreateMan { GET ; SET ;} 10 /// <Summary> . 11 /// created time 12 is /// </ Summary> 13 is [the DataMember] 14 [Display (the Name = " Created " )] 15 public the DateTime CreateDateTime { GET ; SET ;} 16 /// <Summary> . 17 /// movement in the account of 18 is /// </ Summary> . 19 [the DataMember] 20 is [Display (the Name = " movement in the account of " )] 21 is public String TrMan { GET ; SET ;} 22 is /// <Summary> 23 is /// movement time 24 /// </ Summary> 25 [the DataMember] 26 is [Display (the Name = " Alert Time " )] 27 public the DateTime TrDateTime { GET ; SET ;} 28 /// <Summary> 29 /// stamp 30 /// </ Summary> 31 is [the DataMember ] 32 [Display (the Name = " timestamp " )] 33 is public ? TrVersion the DateTime { GET ; SET ;} 34 is }
1 BaseEntity entity = new BaseEntity(); 2 NewExpression newExp = Expression.New(typeof(BaseEntity)); 3 4 MemberInfo createMan = typeof(BaseEntity).GetMember("CreateMan")[0]; 5 MemberInfo trMan = typeof(BaseEntity).GetMember("TrMan")[0]; 6 MemberBinding createManMemberBinding = Expression.Bind(createMan, Expression.Constant("horse")); 7 MemberBinding trManMemberBinding = Expression.Bind(trMan, Expression.Constant("admin")); 8 MemberInitExpression memberInitExpression = Expression.MemberInit(newExp, createManMemberBinding, trManMemberBinding); 9 10 Console.WriteLine(memberInitExpression.ToString());
NewArrayExpression create a new array and may initialize the elements of the new array
1 List<Expression> trees =new List<Expression>() 2 { 3 Expression.Constant("oak"), 4 Expression.Constant("fir"), 5 Expression.Constant("spruce"), 6 Expression.Constant("alder") 7 }; 8 NewArrayExpression newArrayExpression =Expression.NewArrayInit(typeof(string), trees); 9 10 // new [] {"oak", "fir", "spruce", "alder"} 11 Console.WriteLine(newArrayExpression.ToString());
A case of SwitchCase SwitchExpression
SwitchExpression a control expression that by passes control to select multiple processed SwitchCase
1 ConstantExpression switchValue = Expression.Constant(2); 2 SwitchExpression switchExpr =Expression.Switch(switchValue,new SwitchCase[] { 3 Expression.SwitchCase(Expression.Call(null, 4 typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }), 5 Expression.Constant("First")),Expression.Constant(1)), 6 Expression.SwitchCase(Expression.Call(null, 7 typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }), 8 Expression.Constant("Second")),Expression.Constant(2))}); 9 Expression.Lambda<Action>(switchExpr).Compile()();
TryExpression try/catch/finally/fault 块
CatchBlock try block catch statement
1 TryExpression tryCatchExpr =Expression.TryCatch( 2 Expression.Block( 3 Expression.Throw(Expression.Constant(new DivideByZeroException())), 4 Expression.Constant("Try block") 5 ), 6 Expression.Catch( 7 typeof(DivideByZeroException), 8 Expression.Constant("Catch block") 9 ));
UnaryExpression comprises unary expressions
UnaryExpression typeAsExpression =Expression.TypeAs(Expression.Constant(34, typeof(int)),typeof(int?));//等价 34 as int?;
Microsoft Document Address:
System.Linq.Expressions:https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.expressions?view=netframework-4.8