Introduction to Delegate



  • There's a code on the Internet:

    using System;
    

    class a
    {
    public event EventHandler Ev;
    public void EventStart()
    {
    EventHandler temp = Ev;
    if (temp != null)
    temp(this, EventArgs.Empty);
    }
    }
    class demo
    {
    static void Main()
    {
    a A = new a();
    A.Ev += (o, e) => { Console.WriteLine(1); };
    A.Ev += (o, e) => { Console.WriteLine(2); };
    A.Ev += (o, e) => { Console.WriteLine(3); };
    A.EventStart();
    }
    }

    And I was very surprised by that line. EventHandler temp = Ev; Why is the attribution normal? The event and the delegate are different things. The event is a field with the accessories. add removewhich add/ delete methods (delegates) to a "delegal" set. I mean, if it's rude, it's a misappropriation of something like that. Action a = new Action[n]♪ It was particularly surprising that if there were many subscriptions to the event, then at the request of one delegate, they would all be launched. Spread it, please.



  • The point is that all delegates are descendants https://msdn.microsoft.com/ru-ru/library/system.multicastdelegate(v=vs.110).aspx ♪ That is, every delegate is, as you have said, a "delegated body", a container that contains a list of challenges.

    Further, the event is simply a member of the class with a type of delegate (EventHandler (in this case) plus some syntax to enable the signature/recording mechanism to be implemented (the most) add/remove) Given these two things, the attribution is entirely correct (and is done to prevent NullReferenceException in a multi-point environment.

    About calling all the signatures. As I said, every delegate has a list of all challenges. And that's why all the subscriptions are called to the event. The subscriptions are synchronized, and their call is not determined.

    I recommend reading Jeffrey Richter's book "CLR via C#, chapter 11, and John Skita's book "C# for professionals," chapter 2. https://habrahabr.ru/post/198694/ )


    ♪ Strictly speaking, MulticastDelegate really calls for signatures in order to be added. For field-like events, therefore, some form of challenge can be said. This fact, however, is a part of implementation and should not be relied upon. In case of events with accessories add/removethere is no way to rely on order at all, as in general, it is not known how the signature occurs inside.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2