Detailed explanation of using C# delegates (Delegates)
1. What is delegation?
Actually, I have been thinking about how to explain delegation more thoroughly. To be honest, everyone has different opinions because they look at the problem from different angles. Personally, I think it can be understood from the following two points:
(1) In terms of data structure, delegation is a user-defined type like a class.
(2) In terms of design patterns, delegates (classes) provide the abstraction of methods (objects).
Since a delegate is a type, what data does it store?
We know that a delegate is an abstraction of a method, and it stores the addresses of a series of methods with the same signature and return type. When a delegate is called, all methods contained in the delegate will be executed.
2. Definition of delegate type
A delegate is a type, just like a class is a type. Like classes, delegate types must be declared before they can be used to create variables and type objects.
delegate void MyDel(int x);
Delegate type declaration:
(1) Begins with delegate keyword.
(2) Return type + delegate type name + parameter list.
delegate void MyDel(int x);
3. Declare delegate variables
MyDel del1,del2;
4. Initialize delegate variables
(1) Use the new operator
The composition of the operands of the new operator is as follows:
Delegate type name
A set of parentheses, where Contains the name of the method that is the first member of the call list. Methods can be instance methods or static methods.
del1 = new MyDel( myInstObj.MyM1 ); del2 = new MyDel( SClass.OtherM2 );
(2) Use shortcut syntax
quick key syntax, which consists only of method specifiers. This works because there is an implicit conversion between the method name and its corresponding delegate type.
del1 = myInstObj.MyM1; del2 = SClass.OtherM2;
5. Assignment delegate
Since the delegate is a reference type, we can change the method address reference contained in the delegate variable by assigning a value to it. Old references will be reclaimed by the garbage collector.
MyDel del; del = myInstaObj.MyM1; //委托初始化del = SClass.OtherM2;//委托重新赋值,旧的引用将被回收
6. Combining Delegates
Delegates can be combined using additional operators. This operation ultimately creates a new delegate whose call list is the concatenation of copies of the delegate call lists of the two operands.
The delegate is constant and the operand delegate will not be changed after it is created. The delegate combination copies a copy of the operand.
MyDel del1 = myObj.MyMethod; MyDel del2 = SClass.OtherM2; MyDel del3 = del1 + del2; //组合调用列表
7. Delegate addition and subtraction operations
You can use the += operator to add new methods to the delegate.
You can also use the -= operator to remove methods from delegates.
MyDel del = myObj.MyMethod; del += SClass.OtherM2; // 增加方法 del -= myObj.MyMethod; // 移除方法
8. Delegate call
Delegate call is similar to method call. After the delegate is called, each method in the call list will be executed.
Before calling the delegate, you should determine whether the delegate is empty. Calling an empty delegate will throw an exception.
if(null != del) { del();//委托调用 }
9. Anonymous methods
Anonymous methods are methods declared inline when initializing the delegate.
Basic structure:
deleage( 参数 ) { 语句块 }
For example:
delegate int MyDel (int x); //定义一个委托 MyDel del = delegate( int x){ return x; };
From the above we can see that anonymous methods do not declare return values.
10. Lambda expression
Lambda表达式主要用来简化匿名方法的语法。在匿名方法中,delegate关键字有点多余,因为编译器已经知道我们将方法赋值给委托。通过几个简单步骤,我们就可以将匿名方法转换为Lambda表达式:
删除delegate关键字
在参数列表和匿名方法主体之间防Lambda运算符=>。Lambda运算符读作"goes to"。
MyDel del = delegate( int x) { return x; };//匿名方法 MyDel del2 = (int x) => {return x;};//Lambda表达式 MyDel del3 = x => {return x};//简写的Lambda表达式

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

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.

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

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

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.

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

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

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.
