C # event summary and application,
C #Event summary and Application
What is an event??
An event is a special delegate, and a delegate is the basis of an event. Before you introduce an event, you must first introduce the delegate.
In other words:
An event is the method that the Message Drive calls interest through the delegate class. In fact, an event call is an indirect call, just like my proxy in the display.
Publisher and subscriber
When learning events, you must first understand what the publisher is and what the subscriber is:
Notify the publisher of an event (for example, I published a microblog)
A subscriber (for example, I pay attention to Weibo)
Event triggering and Registration
When an event occurs, all subscribers who follow the event will be notified (for example, I published a new Weibo post)
If you want to be notified when an event occurs, you must register the domain name to indicate your interest (for example, if my weibo followers have a new dynamic status)
Event Declaration
The declaration of an event first defines a delegate class, because the event is triggered by calling a series of subscriber registration functions, and the delegate itself can hold multiple signatures and return the same function.
Keyword of event Declaration: event
I wrote an event about the school class.
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;
Namespace event
{
Public delegate void EventHandler (int ringKind); // declare a delegate with Parameters
Public class ShoolRing // defines a publisher class
{
Public event EventHandler OnBellSound; // delegated release
Public void Jow (int ringKind) // implement the logging operation
{
If (ringKind = 1 | ringKind = 2) // you can determine whether the logging is legal.
{
Console. Write (ringKind = 1? "The class bell rings.": "The class bell rings ,");
If (OnBellSound! = Null) // If the delegate event is not null, the method defined by the delegate is called back.
{
OnBellSound (ringKind );
}
}
Else
{
Console. WriteLine ("this ringtone parameter is incorrect! ");
}
}
}
Public class Studens
{
Public void ShowJow (int ringKind) // student Method
{
If (ringKind = 1)
{
Console. WriteLine ("students go to class! ");
}
Else if (ringKind = 2)
{
Console. WriteLine ("students have a break! ");
}
}
}
}
Class Program
{
Static void Main (string [] args)
{
ShoolRing shool = new ShoolRing (); // instantiate the publisher class
Studens stu = new Studens (); // instantiate the subscriber class
Shool. OnBellSound + = stu. ShowJow; // subscribe to events
Shool. Jow (Convert. ToInt32 (Console. ReadLine ()));
Console. ReadLine ();
}
}
}