Reference: http://blog.csdn.net/lastinglate/article/details/5753113
If you are designing events that can be canceled, use CancelEventArgs (not EventArgs) as the base class of Event Data Object e.
Use Case: The subscriber can use e. Cancle to control whether the method for the publisher to trigger an event is executed! Similar to the Form_Closing event mechanism of the form.
CancelEventArgsDemo
By the way, the implementation of static event chain can be referred to: http://www.cnblogs.com/wangiqngpei557/archive/2011/05/19/2051044.html
/1. Customize the EventArgs class to encapsulate event parameter information
Public class ActionCancelEventArgs: System. ComponentModel. CancelEventArgs
{
Private string message;
Public ActionCancelEventArgs (): this (false ){}
Public ActionCancelEventArgs (bool cancel): this (false, String. Empty ){}
Public ActionCancelEventArgs (bool cancel, string message): base (cancel ){
This. message = message;
}
Public string Message {get; set ;}
}
[C-sharp] view plaincopyprint?
// 2. Define the delegate
Public delegate void ActionEventHandler (object sender, ActionCancelEventArgs ev );
// 3. Declare the event (the delegate type is used)
Public static event ActionEventHandler Action;
// 4. Define the event processing function
Protected void OnAction (object sender, ActionCancelEventArgs ev)
{
If (Action! = Null)
{
Action (sender, ev );
}
}
// Register the event handler
Public class BusEntity
{
String time = String. Empty;
Public BusEntity (){
// Add the event handler to the event
Form1.Action + = new Form1.ActionEventHandler (Form1_Action );
}
Private void Form1_Action (object sender, ActionCancelEventArgs e ){
E. Cancel =! DoActions ();
If (e. Cancel)
{
E. Message = "wasn' t the right time .";
}
}
Private bool DoActions (){
Bool retVal = false;
DateTime tm = DateTime. Now;
If (tm. Second <30)
{
Time = "The time is" + DateTime. Now. ToLongTimeString ();
RetVal = true;
}
Else
{
Time = "";
}
Return retVal;
}
Public string TimeString {
Get {return time ;}
}
}
[C-sharp] view plaincopyprint?
Private void btnRaise_Click (object sender, EventArgs e)
{
ActionCancelEventArgs cancelEvent = new ActionCancelEventArgs ();
OnAction (this, cancelEvent );
If (cancelEvent. Cancel)
{
LblInfo. Text = cancelEvent. Message;
}
Else
{
LblInfo. Text = busEntity. TimeString;
}
}