当前位置:网站首页>C EventHandler observer mode

C EventHandler observer mode

2022-07-23 10:48:00 biyusr

C# and java Compare :java Interface is used in .C# Use the delegation mechanism , When it can be used + Operator to register , Direct multicast . and java Generally, a set is used to save observers .

Publisher (Publisher)= Observed (Observable) = Event source (java Medium EventObject,C# Medium sender)
subscriber (Subscriber)= The observer (Observer)= The receiver (java In the inheritance EventLister, Interface , or Observer Interface , C# Due to the entrustment mechanism , No need to inherit interface , Directly by EventHandler Implement callback methods )

When something concerned by other classes or objects happens , Classes or objects can notify them through events . send out ( Or trigger ) The class of events is called “ publisher ”, receive ( Or processing ) The class of events is called “ subscriber ”. In a typical C# Windows Form or Web In the application , Subscribable by control ( Such as buttons and list boxes ) Events triggered by . You can use Visual C# Integrated development environment (IDE) To browse the events published by the control , Select the event to process .IDE Empty event handler methods and code for subscribing to events will be automatically added .

EventHandler by C# Predefined delegates in , Handler methods dedicated to events that represent events that do not generate data .

public delegate void EventHandler(Object sender, EventArgs e)

The event has the following characteristics :

1. The publisher determines when the event is triggered , The subscriber determines what action to perform in response to the event .
2. An event can have multiple subscribers . A subscriber can handle multiple events from multiple publishers .
3. Events without subscribers will never be called .
4. Events are usually used to inform users of actions ( Such as : Button click or menu selection actions in the graphical user interface ).
5. If an event has multiple subscribers , When this event is triggered , Multiple event handlers will be called synchronously . To invoke events asynchronously , See calling synchronous methods asynchronously .
6. You can use events to synchronize threads .
7. stay .NET Framework Class library , Events are based on EventHandler Commission and EventArgs The base class .

The following example demonstrates the above steps , It will be customized EventArgs Classes and EventHandler Used as an event type .

namespace ConsoleApplication2{
       using System;    using System.Collections.Generic;    //  Customize an event class to save event information     public class CustomEventArgs : EventArgs    {
           public CustomEventArgs(string s)        {
               message = s;        }        private string message;        public string Message        {
               get { return message; }            set { message = value; }        }    }    //  Class of broadcast events     class Publisher    {
           //  Use  EventHandler<T>  Declare an event         public event EventHandler<CustomEventArgs> RaiseCustomEvent;        // This method is to do something . Then trigger an event .        public void DoSomething()        {
               //DoSomething…………            //  You can also trigger events before , Execute some other code             OnRaiseCustomEvent(new CustomEventArgs("Did something,hi  This is the news of the event "));        }        // Use virtual methods , Let subclasses override .to allow derived classes to override the event invocation behavior        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)        {
               //  Define a local variable , The last subscriber has been prevented from just checking null Unsubscribe after             EventHandler<CustomEventArgs> handler = RaiseCustomEvent;            //  without   subscriber ( The observer ),  The delegate object will be null            if (handler != null)            {
                   //  Format event messages   String                 e.Message += String.Format(" at {0}", DateTime.Now.ToString());                //  This is the most important sentence .                //  At this time   handler It is already a multicast delegation ( If there are multiple subscribers or observers registered ).                //  Since it is a multicast delegation , You can call each   Callback function  ( Since it is a callback function , The actual execution is determined by the subscriber class ).                // Here comes a this,  On behalf of   Event source ( Or publisher   or   Observed   They all mean the same thing )                handler(this, e);            }        }    }    // Class used to register events     class Subscriber    {
           private string id;        public Subscriber(string ID, Publisher pub)        {
               id = ID;// Register this action , Subscribers should take the initiative , And you can cancel the registration later             pub.RaiseCustomEvent += HandleCustomEvent;        }        //  Implement callback function . After the event , What kind of operation to perform . Here is just a simple print message .        void HandleCustomEvent(object sender, CustomEventArgs e)        {
               // This is the actual operation .            Console.WriteLine(id + " received this message: {0}", e.Message);        }    }    class Class1    {
           static void Main(string[] args)        {
               Publisher pub = new Publisher();            Subscriber sub1 = new Subscriber("sub1", pub);            Subscriber sub2 = new Subscriber("sub2", pub);            //  Call this method to generate events             pub.DoSomething();            Console.WriteLine("Press Enter to close this window.");            Console.ReadLine();        }    }}
原网站

版权声明
本文为[biyusr]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230429245178.html