委托和事件——老鼠跑和猫叫

CatShoutEventArgs 类:猫叫事件参数类,目前的属性只有猫的name

    //EventArgs是包含事件数据的类的父类,作用是事件触发时传递数据
    class CatShoutEventArgs : EventArgs
    {
    
    
        private string name;
        public string Name
        {
    
    
            get{
    
    return name;}
            set {
    
     name = value; } 
        }
    }

Cat类:猫一叫,老鼠就跑

    class Cat
    {
    
    
        private string name;
        public Cat(string name)
        {
    
    
            this.name = name;
        }
        //sender:发送通知让老鼠快跑的那个对象,其实还是老猫
        //agrs:所有接收者需要附件的信息,这里是老猫的名字
        public delegate void CatShoutEventHandler(object sender, CatShoutEventArgs args);
        public event CatShoutEventHandler CatShout;
        public void Shout()
        {
    
    
            Console.WriteLine("喵,我是{0}", name);
            if (CatShout !=null)
            {
    
    
                //声明并实例化一个CatShoutEventArgs对象e
                CatShoutEventArgs e = new CatShoutEventArgs();
                //赋值老猫的名字
                e.Name = this.name;
                //事件触发时,通知所有登记过的对象,并将发送通知的自己(老猫的名字),和老鼠Run需要的数据传递过去(这里需要的还是老猫的名字)
                CatShout(this, e);
            }
        }
    }

Mouse类:边跑边喊 “老猫xx来了,xx(自己的名字)快跑!”

    class Mouse
    {
    
    
        private string name;
        public Mouse(string name)
        {
    
    
            this.name=name;
        }
        //object sender:通知者的对象(老猫的名字)
        //CatShoutEventArgs args:所有接收者需要附件的信息(老鼠1和老鼠2的方法Run都需要老猫的名字,所以这里是两遍老猫的名字)
        public void Run(object sender,CatShoutEventArgs args)
        {
    
    
            Console.WriteLine("老猫{0}来了,{1}快跑",args.Name ,name);
        }
    }

客户端:

        static void Main(string[] args)
        {
    
    
            Cat cat = new Cat("Tom");
            Mouse mouse1 = new Mouse("Jerry");
            Mouse mouse2 = new Mouse("Jack");
			
			//将老鼠的Run方法通过实例化了的委托Cat.CatShoutEventHandler,登记到猫的实践CatShout当中。
			//委托是一个类,可以实例化,委托是对函数的封装,实例成了一个具体的函数
            cat.CatShout += new Cat.CatShoutEventHandler(mouse1 .Run );
            cat.CatShout += new Cat.CatShoutEventHandler(mouse2 .Run );
            //Shout();方法里包含了对事件CatShout的操作,这里就触发了事件CatShout,紧接着方法Shout()就会委托Cat.CatShoutEventHandler通知老鼠的方法Run跟着运行。
            cat.Shout();
        }

猜你喜欢

转载自blog.csdn.net/CharmaineXia/article/details/110791498
今日推荐