Simple mechanism for writing events

Source: Internet
Author: User
Tags define get

 class program    {        static void Main (string[] args)         {            //Create objects of name Class mynamr            name myname = new Na Me ();           //MyName Object get Event Registration event handling method myname_get          &NBSP ; MyName. Get + = new Name.myeventhandler (myname_get);            Console.Write ("\ n Please enter your name:");           //accept user input values and assign values to input variables             string input = Console.re Adline ();           //Assign input variable to myname object's Text property             m Yname. Text = input;       }       //define Myname_get methods for subscribing to events        / /Custom event information class for nested classes of Name class         static void Myname_get (object sender, Name.nameeventargs e)     & nbsp  {           //Output event information and event Publisher's properties             Console.WriteLine ("\ n\t========= Event handling Method ========= ");            Console.WriteLine (" Event information: {0} ", e.tostring ()); nbsp           Console.WriteLine ("Event Publisher: {0}", sender.) ToString ());            Console.WriteLine ("The name you entered is: {0}", ((name) sender). Text);       }   }    public class name    {      &NBSP ; private string _name;       //define MyEventHandler delegate type         public delegate void my EventHandler (object sender, Nameeventargs e);       //define Get events         public event MyEventHandler get;       //define read-write Text properties         internal string text  &nbsp ;     {            get            {                return this._name;        &NBS P  }            set            {      &NBSP ;         This._name = value;               //Call Onget method and pass the name EventArgs class objects                 this. Onget (New Nameeventargs ("Text property Changed"));           }       }  &nbs P    //define Onget method, receive parameters of 1 EventArgs types         void Onget (Nameeventargs e)       & nbsp {           //Trigger Get event delivery two parameters             this. Get (this,e);       }       //Rewrite ToString () method         public ov Erride string ToString ()         {      &nbsp     Return "Name Class object";       }       //custom event information class, inherited from EventArgs class   &N Bsp     public class nameeventargs:eventargs        {            String _args;           //overloaded constructors for assigning parameter values to _args fields             Public Nameeventargs (string s)             {                _args = s;           }           //Rewrite ToString () method, return _args fields             public override string ToString ()           &NBSP ; {                return _args;           }  &N Bsp    }   }}


C # the event mechanism

When the user enters a value, the Text property of the MyName object is assigned a value, the program executes the Onget () method, and the object that passes the custom event class Nameeventargs. The Onget () method fires a get event and passes the object itself and the object of the Nameeventargs class as a parameter. The Myname_get () method subscribed to the get event is notified that the main program calls the Myname_get () method immediately, outputting the string of the custom event class in the method, and the string form and property value of the event Publisher.

Note: It is necessary to understand the relationship between events and delegates in order to grasp the nature of the event mechanism.

Analytical

Most applications, including JavaScript, ActionScript, and so on, have asynchronous event-handling mechanisms that are implemented by multipoint delegates and events in C #.

This design pattern can be called the publisher/Subscriber pattern, the Publisher publishes the event, and multiple classes subscribe to the event (the class must contain a corresponding event-handling method). When the event is triggered, the system notifies each Subscriber that an event has occurred. The event-handling method invoked by the triggering event is implemented by the delegate. In this case, the following points must be noted.

(1) The signature of a delegate type must have two parameters, namely the object and event information that triggered the event.

(2) The event information must be derived from the EventArgs class.

This eliminates the need to know the event information object class when writing the object class that triggered the event. The event information object class can subscribe to or unsubscribe from specific events at run time. Simply put, an event is when the state of an object or class (the publisher) changes, the object or class emits information to inform the Subscriber, and the publisher is also known as the "event source."

Description: There are similar patterns in the event mechanisms of other languages, such as Java, which uses interfaces to implement calls to event receiver response functions at run time using polymorphic methods.

Writing a simple event mechanism requires defining the delegate type, then defining the event through the delegate type, and the last event-handling method subscribing to the event. Assume that a delegate type named Mydel is defined, the event name is onclick, and the definition section is shown in the following code:

Public Delegate return type Mydel (object sender, EventArgs e);

Public event Mydel onclick

Mydel Delegate Object name + = new Mydel ( Event handling method );

// Event-handling method subscriptions onclick Events

onclick + = Delegate Object name ;

// Event handling method Cancel subscription onclick Events

onclick-= Delegate Object name ;

As can be seen from the above code, an event is essentially a special delegate that is subscribed to by multiple methods by means of a multi-point delegate. When an event is triggered, the corresponding event-handling method is referenced.

Simple mechanism for writing events

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.