


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!

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.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software