After reading about the delegation and events, I will send an example to help you remember and help friends who cannot understand the events for the moment.
In the following example, we simply implement the connection between the event and the delegate,
For delegation, we can think like this: it can be a function pointer in C ++, but in C #, for type security and other factors, delegation came into being.
Delegate can treat variables in the same way.
For events, the Windows form programming model is based on events. This is Microsoft's explanation. I have no idea about myself ....
While learning, we can also find that the relationship between the publisher and the subscriber just reflects our "Observer" model.
The so-called "Observer" mode is also called the publishing and subscription mode,
The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. when the status of this topic object changes, it notifies all observer objects so that they can update themselves automatically. (The above definition is transferred to: big talk design mode)
Namespace eventMyWeather
{
Enum Weather
{
Wet on Monday = 1,
Thursday,
Wednesday rain,
Thursday,
Friday rainstorm,
Thunderstorms on Saturday,
Sunday
}
/// <Summary>
/// Create a publisher class
/// </Summary>
Class weatherPublish
{
Weather w; // declare the enumerated variable to store the Weather
Public delegate void Publish (Weather w); // create a delegate
Public event Publish Pub = null; // create an event entrusted with Publish
Public weatherPublish () // constructor to obtain the current weather
{
W = new Weather ();
W = (Weather) Convert. ToInt32 (DateTime. Now. DayOfWeek );
// Console. WriteLine (w );
}
Public void onPain () // publish weather
{
If (Pub! = Null)
{
Console. WriteLine ("weather station announcement! ");
Pub (w );
}
}
}
/// <Summary>
/// Create a subscriber class
/// </Summary>
Class subScriber // create a subScriber
{
Private string name;
Public subScriber (string name)
{
This. name = name;
}
Public void reciveWeather (Weather w)
{
Console. WriteLine (name + "subscribe to weather! ");
Console. WriteLine ("current weather:" + w );
Console. ReadLine ();
}
}
/// <Summary>
/// Publish and subscribe instances
/// </Summary>
Class CCTV
{
Static void Main (string [] args)
{
WeatherPublish wp = new weatherPublish ();
SubScriber zs = new subScriber ("James"); // create a subScriber
SubScriber ls = new subScriber ("Li Si ");
Wp. Pub + = new weatherPublish. Publish (zs. reciveWeather); // Zhang San subscribes to the weather forecast
Wp. Pub + = new weatherPublish. Publish (ls. reciveWeather); // Li Si subscribes to weather forecast
Wp. onPain ();
}
}
}