• 委托 + 事件


    例1:

    例2:

    通知者接口:

    通知者 Boss 类:

    观察者,看股票的同事:

    观察者,看 NBA 的同事:

    客户端代码:

     例3:

        首先增加一个类 CatShoutEventArgs,让它继承 EventArgs(包含事件数据的类的基类 [ MSDN ])

        这个类(EventArgs)的作用就是用来在事件触发时传递数据用的。

        现在写了一个它的一个子类 CatShoutEventArgs,当中有属性 Name 表示的就是 CatShout 事件触发时,需要传递 Cat 对象的名字。

            public class CatShoutEventArgs : EventArgs
            {
              private string name;
              public string Name
              {
                get { return name; }
                set { name = value; }
              }
            }

        然后改写 Cat 类的代码,对委托 CatShoutEventHandler 进行重定义——增加两个参数:

           第一个参数 object 对象 sender 是指向发送通知的对象,

           第二个参数 CatShoutEventArgs 的 args,包含了所有通知接受者需要了解的信息——这里显然就是老猫的名字信息。

            class Cat
            {
              private string name;
              public Cat(string name)
              {
                this.name = name;
              }

              public delegate void CatShoutEventHandler(object sender, CatShoutEventArgs args);

              public event CatShoutEventHandler CatShout;

              public void Shout()
              {
                Console.WriteLine("喵,我是{0}", name);

                if(CatShout != null)
                {
                  CatShoutEventArgs e = new CatShoutEventArgs();
                  e.name = this.name;
                  CatShout(this, e);
                }
              }
            }

        对于老鼠的类:

            class Mouse
            {
              private string name;
              public Mouse(string name)
              {
                this.name = name;
              }

              public void Run(object sender, CatShoutEventArgs args)
              {
                Console.WriteLine("老猫{0}来了,{1}快跑!", args.Name, name);
              }
            }

        所以,对于 private void button1_Click(object sender, EVentArgs e),其中 object sender 就是传递发送通知的对象

      而 EVentArgs 是包含事件数据的类。

  • 相关阅读:
    Spring_配置 Bean(2)
    Spring_HelloWorld
    搭建 Spring 开发环境
    MongoDB快速入门(十三)- 聚合count、distinct和group
    缓存技术,封装好的缓存类
    HTTP协议详解
    C# 缓存技术
    Web Service 的工作原理
    webview长按保存图片
    android Webview 实现js调用java代码实现Activity跳转
  • 原文地址:https://www.cnblogs.com/zhangchaoran/p/7530464.html
Copyright © 2020-2023  润新知