C#之委托与事件

阅读更多

例子摘自<大话设计模式>

委托是一种引用方法的类型,一旦为委托分配方法,委托将与该方法具有完全相同的行为.

事件是说在发生其他类或对象关注的事情时,类或对象可通过事件通知它们.事件对象用event关键字声明

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class CatShotEventArgs : EventArgs
    {
        private string name;
        public string Name  // N为大写
        {
            get { return name; }
            set { name = value; } // value为隐藏值,C#与Java的不同用法
        }
    }

    class Cat
    {
        private string name;
        public Cat(string name)
        {
            this.name = name;
        }
        public delegate void CatShotEventHandler(object sender, CatShotEventArgs args);
        public event CatShotEventHandler CatShout;
        public void Shout()
        {
            Console.WriteLine("Hi, I'm {0}.", name);
            if (CatShout != null)
            {
                CatShotEventArgs e = new CatShotEventArgs();
                e.Name = this.name;
                CatShout(this, e);
            }
        }

    }

    class Mouse
    {
        private string name;
        public Mouse(string name)
        {
            this.name = name;
        }
        public void Run(object sender, CatShotEventArgs args)
        {
            Console.WriteLine("Cat {0} is coming, {1} run! ", args.Name, name);
        }
    }
   
    class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat("Tom");
            Mouse m1 = new Mouse("Jerry");
            Mouse m2 = new Mouse("James");

            cat.CatShout += new Cat.CatShotEventHandler(m1.Run);
            cat.CatShout += new Cat.CatShotEventHandler(m2.Run);

            cat.Shout();
            Console.Read();

        }
    }
}

 结果:


C#之委托与事件_第1张图片
 

  • C#之委托与事件_第2张图片
  • 大小: 9 KB
  • 查看图片附件

你可能感兴趣的:(C#,event)