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