Fork me on GitHub

事件

一、设计要公开事件的类型
1,第一步:定义类型来容纳所有需要发送给事件通知接受者的附加信息

2,第二步:定义事件成员

3,第三步:定义负责引发事件的方法来通知事件的登记对象
4,第四部:定义方法将输入转化为期望事件

//第一步:定义类型来容纳所有需要发送给事件通知接受者的附加信息
    public class NewMailEventArgs:EventArgs
    {
        private readonly string m_from,m_to, 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; }
        }
    }
View Code
    public class MailManager
    {

        //第二步:定义事件成员
        public event EventHandler<NewMailEventArgs> NewMail;

        //第三步:定义负责引发事件的方法来通知事件的登记对象
        protected virtual void OnNewMail(NewMailEventArgs e)
        {
            e.Raise(this, ref NewMail);
        }

        //第四部:定义方法将输入转化为期望事件
        public void SimulateNewMail(string from, string to, string subject)
        {
            NewMailEventArgs e = new NewMailEventArgs(from, to, subject);
            OnNewMail(e);
        }

    }
View Code
    public static class EventArgExtensions
    {
        public static void Raise<TEventArg>(this TEventArg tEventArg, object sender,
            ref EventHandler<TEventArg> eventArgs) where TEventArg : EventArgs
        {

            //Volatile.Read :防止编译器优化掉代码,把temp优化掉了
            EventHandler<TEventArg> temp = Volatile.Read(ref eventArgs);
            if (temp != null)
                temp(sender, tEventArg);
        }
    }
View Code

 

posted on 2017-04-10 21:45  *Hunter  阅读(145)  评论(0编辑  收藏  举报

导航

AmazingCounters.com