This article mainly introduces the in-depth study of += and -= in C#. This article in-depth studies what += and -= do during execution to deepen the understanding and use of C# delegates. Friends in need You can refer to the following
written in front
Why do you suddenly want to talk about entrustment? The reason started from the idea of a colleague. I kept thinking about this on the way to get off work yesterday. Question, if multiple methods are registered to the delegate, will they all be executed? In order to explore the nature, I made a demo to study it.
+=
Everyone knows that delegates inherit from System.MulticastDelegate, and System.MulticastDelegate inherits from System.Delegate. You can register multiple delegates through += method. So have they all been implemented? What is the result of execution? Are the results the same if there is a return value and if there is no return value? Then try to talk about what += has done?
Test code
The code is as follows:
namespace Wolfy.DelegateDemo { public delegate void ShowMsg(string msg); public delegate int MathOperation(int a, int b); class Program { static ShowMsg showMsg; static MathOperation mathOperation; static void Main(string[] args) { showMsg += ShowHello; showMsg += ShowHello1; showMsg("大家新年好啊"); mathOperation += Add; mathOperation += Multiply; int result = mathOperation(1, 2); Console.WriteLine(result.ToString()); Console.Read(); } static void ShowHello(string msg) { Console.WriteLine("哈喽:" + msg); } static void ShowHello1(string msg) { Console.WriteLine("哈喽1:" + msg); } static int Add(int a, int b) { return a + b; } static int Multiply(int a, int b) { return a * b; } } }
You can guess the running result, as shown below:
Yes It can be seen that all those without return values are output, and those with return values only output the results of Mutiply. So what does += do internally? You can take a look at the decompiled code:
The code is as follows:
using System; namespace Wolfy.DelegateDemo { internal class Program { private static ShowMsg showMsg; private static MathOperation mathOperation; private static void Main(string[] args) { Program.showMsg = (ShowMsg)Delegate.Combine(Program.showMsg, new ShowMsg(Program.ShowHello)); Program.showMsg = (ShowMsg)Delegate.Combine(Program.showMsg, new ShowMsg(Program.ShowHello1)); Program.showMsg("大家新年好啊"); Program.mathOperation = (MathOperation)Delegate.Combine(Program.mathOperation, new MathOperation(Program.Add)); Program.mathOperation = (MathOperation)Delegate.Combine(Program.mathOperation, new MathOperation(Program.Multiply)); Console.WriteLine(Program.mathOperation(1, 2).ToString()); Console.Read(); } private static void ShowHello(string msg) { Console.WriteLine("哈喽:" + msg); } private static void ShowHello1(string msg) { Console.WriteLine("哈喽1:" + msg); } private static int Add(int a, int b) { return a + b; } private static int Multiply(int a, int b) { return a * b; } } }
From the above code, you can see that += internally combines the delegates through the Combine static method of the delegate. You can take a look. How is this static method of delegation implemented?
You can see that the CombineImpl method is finally called. The inside of this method is very strange:
There is nothing we want to see I got the code, what is this method used for?
MSDN's explanation
Concatenates the invocation lists of the specified multicast (combinable) delegate and the current multicast (combinable) delegate.
Probably means: Convert the current delegate Adds to the specified multicast delegate set.
After going around a circle, have the delegates with return values been executed? That can only be seen through debugging. (Going around in a circle and back to the editor, alas)
Continue F11 and you will find that you have indeed entered the Add method
It was indeed executed, but when traversing the multicast delegation collection, the previous value was overwritten.
So now we can draw this conclusion: for a delegate without a return value, it will execute as many methods as you register for it, and for a delegate with a return value, it will also register as many methods as you can. How many methods are executed per method, but the return value of the last method is returned.
-=
Since I said +=, as the one who cleans up the mess, -= also has to say it. If you use += in the project, you must use -= to release it. So what does it do internally? Also use the above code, and after outputting the results, use -= to release the resources.
It can be seen that using -= internally calls the delegate's Remove static method.
Using -= ultimately sets the delegate to null. Another meaning of null is a null reference, so that you can wait for garbage collection. The device has been recycled.
Summary
Although this question is very basic, a colleague asked it at the time, so I explained it to him. On the way to get off work, I kept thinking about how to implement it internally. of? Just try to find out by decompiling. But it seems that the CombineImpl method does not give satisfactory results. I haven't seen the specific implementation. Hope this helps!
The above is the detailed content of An in-depth explanation of += and -= of delegation in C#. For more information, please follow other related articles on the PHP Chinese website!

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.

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.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.