search
HomeBackend DevelopmentC#.Net TutorialDetailed 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表达式


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

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.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

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

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

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 C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

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.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

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.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

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# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

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.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

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.