The use of events is similar to a delegate and is implemented in four steps: Declaring a delegate, defining an event, registering an event, invoking an event
Let's look at the definition of the event first.
// Defining Delegates Public Delegate void Publisheventhandler (string msg); // Defining Events Public Event Publisheventhandler Onpublish;
Event registration and de-registration is done using the + = and-= method names, as
Publisher. Onpublish + = method;
Finally, you can invoke the event.
Onpublish (msg);
We also use an example to understand events and learn how events are used.
We now complete a publish subscription process, the Publisher publishes the message, the Subscriber accepts processing
See Sample code
Publisher class:
Public classPublisher {//Defining Delegates Public Delegate voidPublisheventhandler (stringmsg); // Public EventPublisheventhandler Onpublish; Public voidSendMessage (stringmsg) {Console.WriteLine (string. Format ("Publish a message: {0}", msg)); // if(Onpublish! =NULL) { //indicates that the event is registeredonpublish (msg); } } }
subscribers ' classes
Public class Receiver { publicvoid ReceiveMessage (string msg) { Console.WriteLine (string. Format (" receive a message: {0}", msg));} }
define an execution class to see how events are invoked
Public classEventexecutor { Public Static voidRun () {publisher publisher=NewPublisher (); stringmsg ="got paid today."; Receiver Receiver=NewReceiver (); //registering events, subscribingPublisher. Onpublish + =receiver. ReceiveMessage; Publisher. SendMessage (msg); } }
We find that the event is dependent on the existence of the delegate, the use and the delegate is almost the same, are declared before the registration call.
In the example above, it is very simple to use the delegate implementation directly, in the Publisher class we define the delegate object
// using delegates to implement Public Publisheventhandler Publisheventhandler;
The calling class is registered as follows
// using delegates to implement New Publisher.publisheventhandler (receiver. ReceiveMessage);
What exactly is the meaning of the event?
The event is actually using a delegate chain, similar to the delegation of a package, when registering the event, we can only be registered through the form of +=method, and can no longer like the delegate registration of the delegate object directly to assign value.
Other I do not know which is entrusted can not be completed, but also ask the big God pointing
Understanding and application of C # Basic Learning Events