委托 + 事件

例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 是包含事件数据的类。

原文地址:https://www.cnblogs.com/zhangchaoran/p/7530464.html