C # events,
An event is based on a delegate and can provide a publish/subscribe mechanism for any delegate type.
Use the event keyword to define a delegate type as an event.
The following is an example of an event:
// Event publishing class public class PublishEvent {public delegate string Display (string str); public event Display DisplayEvent; // The client code calls this method to trigger the event public void Shows (string str) {if (DisplayEvent! = Null) {DisplayEvent (str) ;}}// event listening class. This class subscribes to the public class Listen1 {public string MakeAlert (string str) {Console. writeLine (str + "Listen1"); return str + "Listen1" ;}} public class Listen2 {public string ShowMsg (string str) {Console. writeLine (str + "Listen2"); return str + "Listen2 ";}}
Client code:
Class Program {static void Main () {PublishEvent pe = new PublishEvent (); Listen1 l1 = new Listen1 (); Listen2 l2 = new Listen2 (); // variables l1 and l2 subscribe to the event pe. displayEvent + = l1.MakeAlert; pe. displayEvent + = l2.ShowMsg; // trigger the event pe. shows ("Event"); Console. readKey ();}}
An event is a Special Delegate (http://www.cnblogs.com/afei-24/p/6762442.html), which is a dedicated delegate for an event-driven model. you can directly call the delegate in the client code to stimulate the function to which the delegate points. However, the event cannot be triggered. The event can only be triggered by the service code. That is to say, in your code, entrusting you not only can arrange who calls the function, but also can directly call it, and events cannot be called directly, but can only be triggered through some operations. In addition, events have all the functions entrusted, including multicast features. That is, an event can have multiple event processing functions, and a delegate can also be a multicast delegate.
Events are encapsulated delegated instances, delegates are types, and events are instances!
The delegate provided by EventHandler <TEventArgs>. NET is also used to define events. (You can go to MSDN for research)