I am reading the. NET Framework today. Program The event principle in design is copied as an example:
Release event: Using System;
Class Mailmanager
{
// Define the mailmsgeventargs type in mailmanager.
Public Class Mailmsgeventargs: eventargs
{
Public Readonly String from, to, subject, body;
// 1. Type Definition information passed to the event Receiver
Public Mailmsgeventargs (string from, string to, string subject, string body)
{
This . From = From;
This . = To;
This . Subject = Subject;
This . Body = Body;
}
}
// 2. The following delegate type defines the prototype of the callback method that the receiver must implement.
Public Delegate Void Mailmsgeventhandler (Object sender, mailmsgeventargs ARGs );
// 3. Event Member
Public Event Mailmsgeventhandler mailmsg;
// 4. The following protected virtual method is used to notify the event registration object
Protected Virtual Void Onmailmsg (mailmsgeventargs E)
{
If (Mailmsg ! = Null )
{
Mailmsg (This, E );
}
}
// 5. The following method converts the input to the expected event. This method is called when new information arrives.
Public Void Simulatearrivingmsg (string from, string to, string subject, string body)
{
// Construct an object to save the information that you want to pass to the notification recipient
Mailmsgeventargs E = New Mailmsgeventargs (from, to, subject, body );
// The time when the virtual method is called to notify the object has occurred.
// If the derived type does not override this virtual method, the object notifies all registered Event Listeners
Onmailmsg (E );
}
}
Listen for events: Using System;
Class Fax
{
/**/ /// <Summary>
///Pass the mailmanager object to the constructor
/// </Summary>
/// <Param name = "mm"> </param>
Public Fax (mailmanager mm)
{
//Construct a mailmsgeventhandler pointing to the faxmsg callback Method
//Delegated instance. Then register the mailmsg event of mailmanager.
Mm. mailmsg+ =NewMailmanager. mailmsgeventhandler (faxmsg );
}
/**/ /// <Summary>
/// Mailmanager will call this method to notify the fax object to receive a new email message.
/// </Summary>
/// <Param name = "sender"> Indicates the mailmanager object. this parameter is used if it is expected to trigger communication with the event. </Param>
/// <Param name = "E"> The additional event information that the mailmanager object wants to provide. </Param>
Private Void Faxmsg (Object sender, mailmanager. mailmsgeventargs E)
{
Console. writeline ("Faxing mail message:");
Console. writeline ("From: {0} \ n to: {1} \ n subject: {2} \ n body: {3} \ n", E. From, E. To, E. Subject, E. Body );
}
/**//// <Summary>
///Logout event
/// </Summary>
/// <Param name = "mm"> </param>
Public Void Unregister (mailmanager mm)
{< br> // construct a mailmsgeventhandler delegate instance pointing to the faxmsg callback method
mailmanager. mailmsgeventhandler callback = New mailmanager. mailmsgeventhandler (faxmsg);
/// log out of mailmanager's mailmsg event
MM. mailmsg -= callback;
}
}