Simple understanding of C # Events

Source: Internet
Author: User

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

It is convenient to define events by using predefined delegate types in the. NET class library. After the publisher triggers the event, the Subscriber executes the event handler: the code and the result of the operation are as follows:

  Public classYiqiok//Event Publishers    {         Public EventEventHandler Lolinvite;//use. NET class Library predefined delegate type definition events         Public voidInvitecoming (stringMsg//Issue Events        {            if(lolinvite!=NULL)//Check to see if event handling methods have been added{Console.WriteLine (msg); Lolinvite ( This,NewEventArgs ());//Triggering Events            }        }            }     Public classClassmate//Event subscribers    {        Private stringname;  PublicClassmate (stringName) {Name=Name; }         Public voidSendresponse (ObjectS,eventargs e)//event handler, to match the predefined delegate type{Console.WriteLine ("from:"+ This. Name +"the reply: has received the invitation, can begin at any time! "); }    }     Public classStart {Static voidMain () {Yiqiok Yiqiok=NewYiqiok ();//InitializeClassmate classmate1 =NewClassmate ("Lna"); Classmate Classmate2=NewClassmate ("Jim"); Classmate Classmate3=NewClassmate ("Cry"); Classmate classmate4=NewClassmate ("Tom"); Yiqiok. Lolinvite+=NewEventHandler (classmate1. Sendresponse);//Subscribe to EventsYiqiok. Lolinvite + =NewEventHandler (Classmate2.            Sendresponse); Yiqiok. Lolinvite+=NewEventHandler (classmate3.            Sendresponse); Yiqiok. Lolinvite+=NewEventHandler (classmate4.            Sendresponse); Yiqiok. Invitecoming ("Yiqiok: Five people turn black to not come??? ");//Send a notification        }    }

Simple understanding of C # events

Related Article

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.