


Take you to review C# delegates, anonymous methods, Lambda, generic delegates, expression tree code examples:
These are commonplace things for the older generation of programmers, nothing new. It is full of charm for the new generation of programmers. In the past, many of the new generation had to go through a long process of study, understanding, and practice to master applications such as delegation and expression trees. Today I try to describe it in a simple way so that everyone can read this blog in five minutes.
The first minute: Commission
Some textbooks and blogs will mention events when talking about delegation. Although events are an instance of delegation, in order to make it easier to understand, today we will only talk about delegation and not events. First a piece of code:
The code below completes a demonstration of a delegated application. A commission consists of three steps:
public partial class WebForm3 : System.Web.UI.Page { //step01:首先用delegate定义一个委托 。 public delegate int CalculatorAdd(int x, int y); protected void Page_Load(object sender, EventArgs e) { //step03:用这个方法来实例化这个委托。 CalculatorAdd cAdd = new CalculatorAdd(Add); //int result = cAdd(5, 6); int result = cAdd.Invoke(5,6); } // step02:声明一个方法来对应委托。 public int Add(int x, int y) { return x + y; } }
Step01: First define a delegate using delegate.
Step02: Declare a method to correspond to the delegate.
Step03: Use this method to instantiate this delegate.
At this point, a delegate should be completed, and the delegate can be called.
Second minute: Anonymous method
As you already know in the last minute, there are three steps to complete a commissioned application. You can’t do it without even one step. If you want to take a big step, be careful if you take a big step and it will hurt your eggs. But Microsoft is not afraid of pulling the strings, and insists on turning three steps into two! Therefore, Microsoft uses an anonymous method to simplify the above three steps. What do you say about anonymous methods? They are completely dispensable in C#. They are just the icing on the cake for C#. Some people ingeniously named them syntactic sugar.
public partial class WebForm3 : System.Web.UI.Page { //step01:首先用delegate定义一个委托 public delegate int CalculatorAdd(int x, int y); protected void Page_Load(object sender, EventArgs e) { //step02:用这样的写法 delegate(int x, int y) { return x + y; },把一个方法赋值给委托 CalculatorAdd cAdd = delegate(int x, int y) { return x + y; }; int result = cAdd.Invoke(5, 6); } }
Step01: First define a delegate using delegate.
Step02: Use this writing method delegate(int x, int y) { return x + y; } to assign a method to the delegate. In fact, this writing method is an anonymous method.
At this time, you will be surprised to find that this is not three steps in front of two steps?
Third minute: Lambda expression
With the addition of a few delegate keywords to an originally simple program, the code suddenly becomes abstruse, and fewer people understand abstruse things, so this can also be used as a bargaining chip for a salary increase. But Microsoft's design philosophy for C# is simplicity and ease of use. Microsoft tried every means to simplify the anonymous method delegate(int x, int y) { return x + y; }, and Lambda appeared. Let me look at several ways to write lambda expressions:
public partial class WebForm3 : System.Web.UI.Page { public delegate int CalculatorAdd(int x, int y); protected void Page_Load(object sender, EventArgs e) { //方法一: CalculatorAdd cAdd1 = (int x, int y) => { return x + y; }; int result1 = cAdd1(5, 6); //方法二: CalculatorAdd cAdd2 = (x, y) => { return x + y; }; int result2 = cAdd2(5, 6); //方法三: CalculatorAdd cAdd3 = (x, y) => x + y; int result3 = cAdd2(5, 6); } }
Method 1: Simply remove the delegate and add "=>" between () and {}.
Method 2: Based on method 1, eliminate all parameter types.
Method Three: If you want to do it, do it more thoroughly and remove {} and the return keyword.
You can write any of these methods, but it is just a nuisance for beginners. Sometimes they see this way of writing, and sometimes they see that way of writing, which makes people fascinated. If no one gives guidance, they will really be confused and difficult. That's the difficulty.
The fourth minute: Generic delegation
As the .net version is not upgraded, the new version must be different from the old version. Otherwise, how can Microsoft engineers report to their boss? So Microsoft is up to something new again.
public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //方法一: Func<int,int,int> cAdd1 = (int x, int y) => { return x + y; }; int result1 = cAdd1(5, 6); //方法二: Func<int, int, int> cAdd2 = (x, y) => { return x + y; }; int result2 = cAdd2(5, 6); //方法三: Func<int, int, int> cAdd3 = (x, y) => x + y; int result3 = cAdd2(5, 6); } }
Whether it is an anonymous method or a Lambda expression, there are two steps to complete the application of a delegate. One is to define a delegate, and the other is to use a method to instantiate a delegate. Microsoft simply combined these two steps into one step. Use Func to simplify the definition of a delegate.
At this point, the application of a delegate can be completed with Func
Fifth minute: Expression tree
In fact, the expression tree has nothing to do with delegation. If it must be related, let's just say that the expression tree is a container for storing delegation. If you have to talk more professionally, the expression tree is a data structure for accessing Lambda expressions. When using a Lambda expression, get it directly from the expression and use Compile() directly. The following code:
public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Expression<Func<int, int, int>> exp = (x, y) => x + y; Func<int, int, int> fun = exp.Compile(); int result = fun(2, 3); } }
What I touched on is very superficial, but at least it allowed everyone to review another article about delegation, anonymous methods, Lambda, generic delegation, and expression trees.
The above is the detailed content of Take you to review C# delegates, anonymous methods, Lambda, generic delegates, expression tree code examples. For more information, please follow other related articles on the PHP Chinese website!

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.


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

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
