C # expression trees to explain (a)

I. Introduction

Always wanted to write custom extensions Dpper article, but which will be designed to parse the Lambda expressions, and analytical Lambda expressions, it is necessary to know the relevant knowledge expression trees. I hope that through the knowledge of the individual modules or can use a little more explanation, can help to know more about the Friends of the Park. Although the rate not fully explain, if they can become a key piece of open, snails also rather pleased.

Second, understand the expression tree

Expression tree to represent the code tree data structure in which each node is a kind of expression, it can be directly written by our original code logic stored in the expression of the way the tree's structure, which can run to resolve when the tree, and then execute, dynamic editing and executing code. In .Net Linq to SQL is inside the parsing of an expression tree.

Here to explain expressions and expression trees down, we all know the expression, such as x + 5 or 5, can be regarded as an expression, and expression trees inside the tree refers to the binary tree, which is a collection of expressions, C # the expression class is a class expression. For an expression tree leaf nodes which are parameters or constants, operators are non-leaf nodes or control characters.

2.1, creating expressions

Lambda expressions Methods:

Expression<Func<int, int,bool>> fun = (x, y) => x < y

This method creates a root type expression ExpressionType.Lambda, Type type of return value type typeof (bool)

Assembly method (an expression tree created by API):

ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
Expression<Func<int, bool>> lambda1 =
    Expression.Lambda<Func<int, bool>>(
        numLessThanFive,
        new ParameterExpression[] { numParam });

We first created two num parameter expression and 5, then LessThan assembled together, the final expression is "num <5", expr node type LessThan, Type type typeof (bool)

Let's take a look at the expression tree inside the structure

First Expression <TDelegate> function is to strongly typed Lambda expressions represented as a form of expression tree data structure, his parent is LambdaExpression, they compare the code shows that the main Lambda expressions, names and all parameters stored in the inside LambdaExpression .

Expression <TDelegate> and LambdaExpression screenshot codes:

image

image

LambdaExpression inside the Body is our expression.

C # expression provides us with a wealth of expression classes, into which category LambdaExpression

image

Method to Return Type "Expression" end, basically a class expression.

Each expression represents the definition and creation methods, reference may be Microsoft's official documentation https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.expressions.binaryexpression?view=netframework-4.8

The following are the most common use of expressions

ConstantExpression : constant expression

ParameterExpression : parameter expression

UnaryExpression : unary operator expression

BinaryExpression that : binary operator expression

TypeBinaryExpression : IS operator expression

ConditionalExpression : conditional expression

MemberExpression : access the field or property expression

The MethodCallExpression : Call to a member function expression

Expression<TDelegate>:委托表达式

2.2、表达式的解析

表达式树解析

通过LambdaExpression类我们可以知道,表达式树包含:参数[Parameters],表达式树类型[NodeType],表达式[Body],返回类型[ReturnType],Lambda表达式的委托[Compile]以及Lambda表达式名称[name],如图所示:

image

表达式解析:

所有的表达式都包含:左节点【Left】,右节点【Right】,类型【NodeType】,不同的表达式还会有其他属性,这里的左右节点依旧是表达式。

下图是BinaryExpression表达式截图

image

表达式树和表达式里面的类型NodeType是一个枚举,一共有85个类型,有兴趣的朋友可以去了解下。

常用的类型如下:

ExpressionType.And:C#中类似于&

ExpressionType.AndAlso:C#中类似于&&

ExpressionType.Or:C#中类似于|

ExpressionType.OrElse:C#中类似于||

ExpressionType.Equal:C#中类似于==

ExpressionType.NotEqual:C#中类似于!=

ExpressionType.GreaterThan:C#中类似于>

ExpressionType.GreaterThanOrEqual:C#中类似于>=

ExpressionType.LessThan:C#中类似于<

ExpressionType.LessThanOrEqual:C#中类似于<=

ExpressionType.Add:C#中类似于+

ExpressionType.AddChecked:C#中类似于+

ExpressionType.Subtract:C#中类似于-

ExpressionType.SubtractChecked:C#中类似于-

ExpressionType.Divide:C#中类似于/

ExpressionType.Multiply:C#中类似于*

ExpressionType.MultiplyChecked:C#中类似于*

2.3、编译表达式树

在表达式创建那,我们组合创建了一个Lambda表达式,那么应该怎么使用它呢?在“表达式的解析”里面,LambdaExpression类和Expression<TDelegate>类都有一个Compile的方法,学名是Lambda表达式的委托,其实就是Lambda表达式编译函数的委托,所以我们只需要调用他,得到的结果就是一个函数方法。

代码修改如下:

ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
Expression<Func<int, bool>> lambda1 =
    Expression.Lambda<Func<int, bool>>(
        numLessThanFive,
        new ParameterExpression[] { numParam });

Console.WriteLine($"Lambda的内容:{lambda1.ToString()}");

//表达式的编译
var func = lambda1.Compile();
Console.WriteLine ($ "Lambda operating results of: {FUNC (. 6)} ");

operation result

image

Third, the summary

Here we do a basic expression of explanation, I believe we have a preliminary understanding of the Lambda expressions, here we will continue to explain to traverse an expression tree.

Guess you like

Origin www.cnblogs.com/snailblog/p/11521043.html