Events are based on delegates and can provide a publish \ Subscribe mechanism for any kind of delegate type.
Use the event keyword to define a delegate type as an event.
Here's an example of an event:
//Event Publishing Class Public classpublishevent { Public Delegate stringDisplay (stringstr); Public EventDisplay displayevent; //the client code triggers the event by calling this method Public voidShows (stringstr) { if(Displayevent! =NULL) {displayevent (str); } } } //event Listener class, this class subscribes to events Public classListen1 { Public stringMakealert (stringstr) {Console.WriteLine (str+"Listen1"); returnSTR +"Listen1"; } } Public classListen2 { Public stringShowMsg (stringstr) {Console.WriteLine (str+"Listen2"); returnSTR +"Listen2"; } }
Client code:
classProgram {Static voidMain () {publishevent PE=Newpublishevent (); LISTEN1 L1=NewListen1 (); LISTEN2 L2=NewListen2 (); //variables L1 and L2 subscribed to the eventPe. Displayevent + =L1. Makealert; Pe. Displayevent+=L2. ShowMsg; //Triggering EventsPe. Shows ("Events"); Console.readkey (); } }
An event is a special delegate (http://www.cnblogs.com/afei-24/p/6762442.html), which is a dedicated delegate for the event-driven model. You can invoke the delegate directly in the customer code to fire the function that the delegate points to, and the event cannot be The triggering of an event can only be triggered by the service code itself. That is to say that in your code you can not only arrange who is its calling function, but also call it directly, and the event cannot be called directly, only triggered by certain actions. In addition to this, the event has all the functions of the delegate, including the multicast attribute. That is, an event can have more than one event handler, and a delegate can also be a multicast delegate.
An event is a encapsulated instance of a delegate, a delegate is a type, and an event is an instance!
Eventhandler<teventargs>. NET comes with a delegate that is also used to define events. (Can go to MSDN Research)
Events of C #