An in-depth explanation of the + = and-= of Delegates in C #

Source: Internet
Author: User
This article mainly introduces C + + and-= in-depth research, this article in-depth study of + = and-= in the implementation of what has been done, deepen the understanding and use of C # delegation, the need for friends can refer to the next

Write in front

Why do you suddenly want to talk about the Commission? The reason, starting from a colleague's idea, yesterday after work on the road has been thinking about this problem, if the Commission to register a number of methods, will be executed? For the sake of inquiry, we got a demo study.

+=

We all know that the delegate inherits from System.MulticastDelegate, and System.MulticastDelegate inherits from System.Delegate, and can register multiple methods by means of + =. So are they all executed? What is the result of the implementation? Is there a return value and no return value for the same result? Then try to talk about what the + + 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 ("Good Year for everyone");              Mathoperation + = ADD;            Mathoperation + = Multiply;            int result = Mathoperation (1, 2); Console.WriteLine (Result.            ToString ());        Console.read ();        } static void Showhello (String msg) {Console.WriteLine ("Hello:" + msg);        } static void ShowHello1 (String msg) {Console.WriteLine ("Hello 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 results of the run, such as:

You can see that there is no return value of the output, there is a return value only output the results of the mutiply, then + = internal do what? You can look at the anti-compilation 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, n            EW showmsg (Program.showhello));            Program.showmsg = (showmsg) delegate.combine (program.showmsg, New ShowMsg (PROGRAM.SHOWHELLO1));            Program.showmsg ("Good Year for everyone");            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 ("Hello:" + msg);      } private static void ShowHello1 (String msg) {      Console.WriteLine ("Hello 1:" + msg);        } private static int Add (int a, int b) {return a + B;        } private static int Multiply (int a, int b) {return a * b; }    }}

The above code can be seen in the + = inside the delegate by the Combine static method to combine the delegate, you can see how the delegation of this static method is implemented.

You can see the final call to Combineimpl this method, this method inside is very strange:

There is no code that we want to see, so what does this method do?

Explanation of MSDN

Concatenates the invocation lists of the specified multicast (combinable) delegate and the current multicast (combinable) Delegate.

The idea is to add the current delegate to the specified set of multicast delegates.

Around a circle so there is a return value of the delegate, in the end executed it? That can only be seen through debugging. (around a circle, back to the editor, alas)

Continue F11 you'll find that you did enter the Add method

It does, but it overwrites the previous value when traversing the multicast delegate collection.

So now you can conclude that there is no return value of the delegate, how many methods you register to it, how many methods it executes, and the delegate that returns the value, how many methods are executed by the same number of methods, but returns the return value of the last method.

-=

Since said + =, so as to clean up the mess of-= also have to say. The use of + = In the project is used to release with-=. So what did it do inside? Also use the above code, after outputting the result, use-= to release the resource.

As you can see, using-= internally is the Remove static method that invokes the delegate.

Using-= ultimately is to set the delegate to null, and the other means null reference, so you can wait for the garbage collector to recycle.

Summarize

Although the problem is very basic, a colleague asked at that time, he said to him, on the way from work has been thinking, how the interior is achieved? Try to find out by way of anti-compilation. But seemingly combineimpl this method, the results are not very satisfied. Did not see the specific implementation. Hope to help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.