Expression tree can be said to be one of the cores of Linq. Why is it one of the cores of Linq? Because the expression tree makes c# no longer just compile to IL, we can generate an expression tree through c#, use the result as an intermediate format, and convert it into the native language on the target platform. Such as SQL. This is how our commonly used Linq to sql generates SQL.
Expression tree was introduced after .NET 3.5. It is a powerful and flexible tool (such as used to construct dynamic queries in LINQ).
Let’s first take a look at the API interface of the Expression class:
namespace System.Linq.Expressions { // // 摘要: // 以表达式目录树的形式将强类型 lambda 表达式表示为数据结构。此类不能被继承。 // // 类型参数: // TDelegate: // System.Linq.Expressions.Expression`1 表示的委托的类型。 public sealed class Expression<TDelegate> : LambdaExpression { // // 摘要: // 将表达式树描述的 lambda 表达式编译为可执行代码,并生成表示该 lambda 表达式的委托。 // // 返回结果: // 一个 TDelegate 类型的委托,它表示由 System.Linq.Expressions.Expression`1 描述的已编译的 lambda 表达式。 public TDelegate Compile(); // // 摘要: // 生成表示 lambda 表达式的委托。 // // 参数: // debugInfoGenerator: // 编译器用于标记序列点并批注局部变量的调试信息生成器。 // // 返回结果: // 包含 lambda 的已编译版本的委托。 public TDelegate Compile(DebugInfoGenerator debugInfoGenerator); // // 摘要: // 创建一个与此表达式类似的新表达式,但使用所提供的子级。如果所有子级都相同,则将返回此表达式。 // // 参数: // body: // 结果的 System.Linq.Expressions.LambdaExpression.Body 属性。 // // parameters: // 结果的 System.Linq.Expressions.LambdaExpression.Parameters 属性。 // // 返回结果: // 此表达式(如果未更改任何子级),或带有更新的子级的表达式。 public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters); protected internal override Expression Accept(ExpressionVisitor visitor); } }
The syntax of the expression tree is as follows:
Expression<func>> = (param) => lamdaexpresion;</func>
For example:
Expression<Func<int, int, int>> expr = (x, y) => x+y;
We run the above code and view this expression tree under VS debugging mode:
You can see The expression tree is mainly composed of the following four parts:
1. Body part
2. Parameters part part
3. NodeType node type
4.Lambda expression type
In the above code, the main body is: x+y, and the parameters are (x, y), NodeType is Lambda expression, and the return value is int
The main part can be an expression, but it cannot contain statements. For example: I define a delegate. The Lambda expression can be written like this
Func<int, int, int> func = (x, y) => x + y;
or it can be written like this:
Func<int, int, int> func = (x, y) => { return x + y; };
However, in the expression tree type, only the first way of writing can be used. If the second way of writing is used, the compiler will report an error: Cannot convert a lambda expression with a statement body into an expression tree.
In addition to the above writing method, the expression tree can also be written like this:
ParameterExpression pex1 = Expression.Parameter(typeof(int), "x");//第一个参数 ParameterExpression pex2 = Expression.Parameter(typeof(int), "y");//第二个参数 BinaryExpression bexp = Expression.Add(pex1, pex2);//加法 var lambdaExp = Expression.Lambda<Func<int, int, int>>(bexp, new ParameterExpression[] {pex1,pex2 });
VS debugging In mode, you can see that the expression trees generated by the two writing methods are the same
Compile the expression tree into a delegate
LambdaExpression is a type derived from Expression. The generic class Expression
LambdaExpression has a Compile method that creates a delegate of the appropriate type. The Compile method of Expression
Expression<Func<int, int, int>> expr = (x, y) => x + y; ParameterExpression pex1 = Expression.Parameter(typeof(int), "x");//第一个参数 ParameterExpression pex2 = Expression.Parameter(typeof(int), "y");//第二个参数 BinaryExpression bexp = Expression.Add(pex1, pex2);//主体,加法 //使用Expression.Lambda方法,创建一个委托类型已知的Expression Expression<Func<int,int,int>> lambdaExp = Expression.Lambda<Func<int, int, int>>(bexp, new ParameterExpression[] { pex1, pex2 }); Func<int,int,int> tDelegate = lambdaExp.Compile();//编译成委托 Console.WriteLine(tDelegate(1, 3)); Console.Read();
We run the above code and the result is: 4. We wrote a lot of code, which essentially calculated the result of 1+3 using an expression tree.
The above is the detailed content of A brief introduction to expression trees in C#. For more information, please follow other related articles on the PHP Chinese website!

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1
Easy-to-use and free code editor