Event is a class that is based on the Windows message Processing mechanism, and the encapsulation is better, so that developers can develop powerful event-based applications without needing to know the underlying message-handling mechanism.
Delegate (delegate) delegates can be understood as function pointers, unlike delegates that are object-oriented, type-safe, and derive various special types of delegates such as Task,action,func.
Relationship of events and delegates:
We can simply divide the event programming into two parts: the class in which the event occurs (called the event generator in writing) and the class that the event receives processing. The class in which an event occurs means that an event is triggered in this class, but the class does not know which object or method will receive and handle the event it fires. What is needed is a medium between the sender and the receiver.
This medium is delegated (delegate) in the. NET framework. In the class where the event is received, we need to have a way to handle the event.
Generally speaking, an event is a special kind of delegate.
Here's an example of creating your own event.
1, first create a own EventArgs class. EventArgs is the base class for the class that contains the event data, which does not contain event data and is used by events that do not pass state information to the event handler when the event is raised. If the event handler requires state information, the application must derive a class from this class to hold the data. Because we want to include the key information in our keyboard key event, we want to derive a KeyEventArgs class to save the key information so that we know which key to press later.
Internal class keyeventargs:eventargs{ privatechar keyChar; Public Char Base () { this. KeyChar = KeyChar; } Public Char KeyChar { get { return KeyChar;}} }
2. Create an event class Keyinputmonitor, which monitors the input of keyboard keys and triggers an event:
Internal classkeyinputmonitor{//create a delegate with a return type of void, two parameters Public Delegate voidKeydownhandler (Objectsender, KeyEventArgs e); //Associates the created delegate with a specific event, where the specific event is KeyDown Public EventKeydownhandler KeyDown; Public voidRun () {BOOLFinished =false; Do{Console.WriteLine ("Input a char" ); stringResponse =Console.ReadLine (); CharResponsechar = (Response = ="") ?' ':Char. ToUpper (response[0] ); Switch(Responsechar) { Case 'X': Finished=true; Break; default: //parameters to get key informationKeyEventArgs KeyEventArgs =NewKeyEventArgs (Responsechar); //Triggering EventsKeyDown ( This, KeyEventArgs); Break; } } while( !finished); }}
Note here that KeyDown (this, KeyEventArgs) is, this is the statement that triggered the event, and the event is referred to the Keydownhandler delegate to handle, the delegate specifies the event handling method to handle the event, this is the event receiver's class thing. The parameter this refers to the object that triggered the event itself, and KeyEventArgs contains the key information. 3, finally create a class of event receiver, this class first produces a delegate instance, and then adds this delegate instance to the event list that produces the event object, this process is called the subscription event. Then provide a method to echo the key information.
Internal classeventreceiver{ Publiceventreceiver (Keyinputmonitor monitor) {//generates a delegate instance and adds it to the list of events generated by KeyinputmonitorMonitor. KeyDown + =NewKeyinputmonitor.keydownhandler ( This. OnKeyDown); } Private voidOnKeyDown (Objectsender, KeyEventArgs e) { //The Real event handler functionConsole.WriteLine ("Capture key: {0}", E.keychar); }}
4, see how to call
Public class mainentrypoint{ publicstaticvoid Start () { // Instantiate an event sender new keyinputmonitor (); // instantiate an event sink New Eventreceiver (monitor); // Run Monitor. Run ();} }
Steps required for using events in C #: 1. Create a delegate 2. Associates the created delegate with a specific event (. NET class Library Many of the events are already custom-made, so they have a corresponding delegate, in writing the associated event handler-that is, when an event occurs when we want to execute the method we need to have the same signature as this delegate) 3. Writing event handlers 4. Generate a delegate instance using a written event handler 5. Add this delegate instance to the event list that produces the event object, which is called subscribing to the event
Note: The event plays a limiting role. Events are special types of multicast delegates that can only be called from the class or struct in which they are declared (the Publisher Class). If the event is subscribed to by another class or struct, its event handler method is called when the event is raised by the Publisher class.
Event resolution for C # events