自定义CancelEventArgs类,封装事件参数信息,实现e.Cancle=true取消机制。

参考文章:http://blog.csdn.net/lastinglate/article/details/5753113

如果您正在设计可取消的事件,请使用CancelEventArgs(而非是EventArgs)作为事件数据对象e的基类。

 使用场景:订阅者可以通过e.Cancle来控制发布者引发事件的方法是否被执行!类似窗体的Form_Closing事件机制。

CancelEventArgsDemo

 顺便有关静态事件链的实现,可以参考:http://www.cnblogs.com/wangiqngpei557/archive/2011/05/19/2051044.html

 /1.自定义EventArgs类,封装事件参数信息  

    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 { getset; }  
    }  

[c-sharp] view plaincopyprint?
//2.定义委托  
       public delegate void ActionEventHandler(object sender, ActionCancelEventArgs ev);  
       //3.声明事件(用到委托类型)  
       public static event ActionEventHandler Action;  
        //4.定义事件处理函数  
       protected void OnAction(object sender, ActionCancelEventArgs ev)  
       {  
           if (Action != null)  
           {  
               Action(sender, ev);  
           }  
       }  

//注册事件处理程序  
public class BusEntity  
    {  
        string time = String.Empty;  
        public BusEntity() {  
            //将事件处理程序添加到事件  
            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);  
          //抛出事件后,将根据询问订阅者是否取消事件的接受e.Cancle=False/True,来执行后续的代码。
          if (cancelEvent.Cancel)  
          {  
              lblInfo.Text = cancelEvent.Message;  
          }  
          else  
          {  
              lblInfo.Text = busEntity.TimeString;  
          }  
      }  
原文地址:https://www.cnblogs.com/51net/p/2498137.html