zoukankan      html  css  js  c++  java
  • 事件

    一、设计要公开事件的类型
    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
    学习永不止境,技术成就梦想。
  • 相关阅读:
    重头学习java(4)数组
    java collections读书笔记(1)综述
    重头再学习java(3):数值类型的相互转换
    如何学习java(转)
    c++中的变量做数组长度
    .H和.CPP的作用
    内存操作函数
    HTTP工作原理及HTTP请求、响应报文解读
    bdb_db_open: warning – no DB_CONFIG file found in directory /var/lib/ldap:
    用SWAT图行化配置Samba
  • 原文地址:https://www.cnblogs.com/zd1994/p/6691113.html
Copyright © 2011-2022 走看看