It is difficult to understand the events and delegation in the. NET Framework. In particular, it takes some time to learn the special types of delegation.
The following uses the observer mode as a simple example to help beginners.
First, create a console application. The Code is as follows:
Program. CS:
Using system;
Using system. Collections. Generic;
Using system. text;
Namespace observerpattern
{
/// <Summary>
/// Declare a delegate type (that is, a function template pointing to the function address, one of the five. Net types)
/// </Summary>
Public Delegate void personeventhandler ();
/// <Summary>
/// Declare an observer
/// </Summary>
Public class light
{
Private person = NULL;
Public Light (person P)
{
Person = P;
Person. backorout + = new personeventhandler (p_backorout );
}
Private void p_backorout ()
{
If (person. dir. toupper () = "out ")
{
Console. writeline ("if you want to exit, the light will automatically go out. ");
}
Else if (person. dir. toupper () = "back ")
{
Console. writeline ("when you return home, the light will automatically light up. ");
}
}
}
/// <Summary>
/// Declare a subject
/// </Summary> 〉
Public class person
{
Private string dir;
Public String dir
{
Get
{
Return dir;
}
Set
{
Dir = value;
}
}
Public Person (string DIR)
{
This. dir = dir;
}
// Declare an event (that is, a delegate-type variable)
Public event personeventhandler backorout;
Public void onbackorout ()
{
If (backorout! = NULL)
{
// Execute the event (that is, the delegate state function)
Backorout ();
}
}
}
/// <Summary>
/// Main program
/// </Summary>
Class Program
{
Static void main (string [] ARGs)
{
Console. writeline ("select whether you want to go out or go home. Enter out when you go out. Enter back when you go home. ");
String dir = console. Readline ();
Do
{
Person P = new person (DIR );
Light L = new light (P );
P. onbackorout ();
Console. writeline ("select whether you want to go out or go home. Enter out when you go out. Enter back when you go home. ");
Dir = console. Readline ();
} While (Dir! = "Exit ");
}
}
}
It is easier to understand observer under events and delegation under the. NET Framework.