.net EventHandler 事件处理

 通常定义事件 都是通过自定义委托的方式来实现, 今天使用EventHandler   委托来定义事件:

    public class NewMailEventArgs : EventArgs
    {

        private readonly string m_from;
        private readonly string m_to;
        private readonly string m_subject;

        public NewMailEventArgs(string from, string to, string subject)
        {
            m_from = from;
            m_to = to;
            m_subject = subject;
        }


        public string From { get { return m_from; } }
        public string To { get { return m_to; } }
        public string Subject { get { return m_subject; } }
  
    }

    //定义事件成员
    public class MailManager
    {
        public event EventHandler<NewMailEventArgs> NewMail;

        public virtual void OnNewMail(NewMailEventArgs e)
        {
            //Volatile线程 Threading.Tasks
            EventHandler<NewMailEventArgs> temp = Volatile.Read(ref NewMail);

            if (temp != null)
            {
                temp(this, e);
            }
        }

        public void SimulateNewMail(string from, string to, string subject)
        {
            //构造一个对象来容纳想传给通知接受者的信息
            NewMailEventArgs e = new NewMailEventArgs(from, to, subject);
            
            //调用虚方法通知对象事件已发生
            //如果没有类型重写该方法,我们的对象将通知事件的所有等级对象
            OnNewMail(e);
        }  

    }

    public sealed class Fax {
        /// <summary>
        /// 将MailManager 对象传给构造器
        /// </summary>
        /// <param name="mail"></param>
        public Fax(MailManager mail)
        {
            mail.NewMail += FaxMsg;
        }

      
        /// <summary>
        /// 注销事件
        /// </summary>
        /// <param name="mail"></param>
        public void UnFax(MailManager mail)
        {
            mail.NewMail -= FaxMsg;
        }

        //新电子邮件到达时,mailManager调用这个方法
        public void FaxMsg(object sender, NewMailEventArgs e)
        {
            Console.WriteLine("Faxing mail message:");
            Console.WriteLine(" From={0},To={1},Subject={2}", e.From, e.To, e.Subject);
        }
 
    }

    static void Main(string[] args)
        {
             
            MailManager mail = new MailManager();

            Fax fax = new Fax(mail);

            mail.SimulateNewMail("from0", "to1", "subject2");

        }
原文地址:https://www.cnblogs.com/dragon-L/p/5348536.html