C # simple understanding of events,

Source: Internet
Author: User

C # simple understanding of events,

Events are an important feature of C. Events mainly involve publishers, subscribers, and event handlers.

Using the pre-defined delegate type in the. net class library, you can easily define events. After the publisher triggers an event, the subscriber executes the event processing function. The code and running result are as follows:

Public class Yiqiok // event publisher {public event EventHandler LolInvite; // use. NET class library pre-defined delegate type definition event public void InviteComing (string msg) // issue event {if (LolInvite! = Null) // check whether an event handling method is added {Console. writeLine (msg); LolInvite (this, new EventArgs (); // trigger event }}public class Classmate // event subscriber {private string name; public Classmate (string Name) {name = Name;} public void SendResponse (object s, EventArgs e) // event processing function, which must match the predefined delegate type {Console. writeLine ("from:" + this. name + "reply: you have received the invitation and can start at any time! ") ;}} Public class Start {static void Main () {Yiqiok yiqiok = new Yiqiok (); // initialize Classmate classmate1 = new Classmate (" Lna "); classmate classmate2 = new Classmate ("Jim"); Classmate classmate3 = new Classmate ("Cry"); Classmate classmate4 = new Classmate ("Tom"); yiqiok. lolInvite + = new EventHandler (classmate1.SendResponse); // subscribe to the event yiqiok. lolInvite + = new EventHandler (classmate2.SendResponse); yiqi OK. LolInvite + = new EventHandler (listener); yiqiok. LolInvite + = new EventHandler (listener); yiqiok. InviteComing ("yiqiok ??? "); // Send a notification }}

 

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.