C# events (including complete declaration and simple declaration)

  1. Events are based on delegation and need to be constrained by delegation.
    1. Constrains the information that an event can send to responders (subscribers)
    2. Constrains the messages that event responders (subscribers) can receive
    3. The event handler needs to meet the above two requirements at the same time to subscribe to the event
    4. Only delegate instances can hold event handlers through record and reference methods
  2. The essence of the event is a wrapper of the delegate field
    • This wrapper restricts access to delegate fields, making the program safer
    • Events hide most of the functions of the delegate instance from the outside world, only exposing the functions of adding and removing event handlers.
    • Only the += or -= operator can be used on the right side of the event
  3. The event is a member and can only be written in the class
  4. The function of events is to allow objects or classes to have notification capabilities
  5. 5 components of the event model
    • Event owner (publisher)
    • event member
    • Responders (subscribers) to events
    • Event handler - essentially a callback method
    • event subscription
  6. full statement of events
    1. First, create the owner (publisher) of the event
      public class MessageEvent
          {
          }
    2. Create event member

      Before creating an event member, you need to create a delegate to constrain it. The name of this type of delegate is usually xxx+EventHandler, which means that the delegate is dedicated to serving events. The delegate generally contains two parameters (evolved from Win32API). The first The first parameter is the owner (publisher) of the event, and the second parameter is the event message data to be transmitted to the responder (subscriber) after the event occurs. Create this class below

      //创建EventArgs的派生类,包含需要传送给事件的信息
          public class MessageEventArgs : EventArgs
          {
              public string name { get; set; }
              public string message { get; set; }
          }

      When creating this class, the EventArgs class is usually inherited. For the sake of unification and standard practice, the name is usually xxx+EventArgs. If there is no data that needs to be transmitted here, the second parameter of the delegate can be filled in as the EventArgs class. This class For event handlers that do not require passing data

      public delegate void SendMessageEventHandler(MessageEvent messageEvent, EventArgs e);

      Now you can start creating event members

      //创建委托
          public delegate void SendMessageEventHandler(MessageEvent messageEvent, MessageEventArgs e);
      public class MessageEvent
          {
              private  SendMessageEventHandler sendMessageEventHandler;
              //声明事件,用委托类型来约束事件参数
              public  event SendMessageEventHandler SendMessage
              {
                  add//添加器
                  {
                      sendMessageEventHandler += value;
                      //这里写的代码会在订阅事件的时候同时执行
      
                  }
                  remove//移除器
                  {
                      sendMessageEventHandler -= value;
                      //这里写的代码会在移除事件的时候同时执行
                  }
              }
          }

      First, create a field based on the delegate type created above. This field is used to store and reference the event handler. This field does not need to be accessed by the outside world, so the access level is private. The access level of event members is public. When creating event members, you need to add the keyword event and use the corresponding delegate type to constrain the event.

      The event is followed by a statement block, which is used to write the adder and remover of the event. The value of the adder and remover represents the event handler passed in from the outside. At the same time, the code written in the adder and remover It will take effect when the event is subscribed.

      The name of the event should be a verb or verb phrase with tense, which means that you are doing xxx thing or finished xxx thing

    3. Create responders (subscribers) to events

      public class MessageEventAction
          {
          }
      

      Then add the event handler in the responder (subscriber) of the event

      //SendMessage事件的处理器
              public  void Action(MessageEvent messageEvent, MessageEventArgs e)
              {
      
                  
                  MessageBox.Show($"name:{e.name},message:{e.message}");//这个方法是让wpf出现弹窗,在弹窗中显示内容
                      
              }
    4. Write the method that triggers the event in the event owner

       //事件拥有者内部方法触发事件
              protected  void OnEventAction(string name, string message)
              {
      
      
                  
                  if (sendMessageEventHandler != null)//没有地方订阅事件时,不触发
                  {
                      MessageEventArgs e = new MessageEventArgs();
                      e.name = name;
                      e.message = message;
      
                      sendMessageEventHandler.Invoke(null, e);
                  }

      Usually, the method that triggers the event is named Onxxx, the access level should be Protected, and cannot be accessed by the outside world. The triggering of the event can only be done by the owner (publisher) of the event.

    5. Finally subscribe to the event

      class program
      {
          static void Main(string[] args)
          {
              MessageEvent messageEvent = new MessageEvent();
              MessageEventAction messageEventAction = new MessageEventAction();
              messageEvent.SendMessage += messageEventAction.Action;
              string name = "hello";
              string message = $"world";
              messageEvent.EventAction(name, message);
          }
      }

      In this way, a complete event declaration is completed, which includes the event owner (publisher), event members, event responders (subscribers), event handlers, and event subscriptions

  7. Simple statement of events

    1. The simple declaration of an event is a syntax sugar that provides us with great convenience when declaring an event, but it does not make it convenient for us to learn and understand the event. The following will show the difference between the complete declaration and the simple declaration of the event.

    2. Creation of event members

      public  event SendMessageEventHandler SendMessage;//事件的简略声明格式

      First of all, when creating event members, we no longer need to define the adders and removers of the event ourselves, nor do we need to create a delegate field (note that it is a delegate field, not a delegate type, the delegate type still needs to be created), it seems It is very concise, but it will also make beginners mistakenly think that this is a delegate type field with the event keyword.

    3. How to trigger an event

      protected  void EventAction(string name, string message)
              {
      
      
                  
      
                  if (this.SendMessage != null)
                  {
                      MessageEventArgs e = new MessageEventArgs();
                      e.name = name;
                      e.message = message;
      
                      this.SendMessage.Invoke(this, e);
                  }
      
      
              }

      Since the simple declaration format does not require us to create a delegate field, we have no choice but to use the name of the event instead. Under normal circumstances, the right side of the event can only be followed by the += and -= operators. Here is The self-contradiction caused by syntactic sugar also makes it easy for beginners to think that the right side of an event can be used with other operators, deepening the misunderstanding of "events are fields".

      When using syntax sugar to declare simple events, the system actually declares a field of the delegate type for us automatically. This field can be seen through decompilation.

 This article is the notes of watching Teacher Liu Tiemeng's "Introduction to C#". For more detailed content, you can watch Teacher Liu's video.

Station b: Detailed introduction to C# language Detailed explanation of 022 event (Part 2)_bilibili_bilibili

youtube: Detailed introduction to C# language (022) - Detailed explanation of events (Part 2) - YouTube

        ​​                        ​​​​​

Guess you like

Origin blog.csdn.net/zsdxdfs/article/details/131566842