委托与事件的关系

2018-06-23 21:57:42来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

namespace eventDelegate
{
    //通水人
    class middleBoy
    {
        //
     public   delegate void playGame(object obj, playGameEventArgs e);
    }


    //消息
    class playGameEventArgs:EventArgs
    {
        public string name{get;set;}

    }
    class Boss
    {
        public static void notify(object obj, playGameEventArgs e)
        {
            Console.WriteLine(e.name + " 玩游戏了");
        }
    }
    //管理人2
    class Admin
    {
        public static void notify(object obj, playGameEventArgs e)
        {
            Console.WriteLine(e.name + " 玩游戏了");
        }
    }
    class employee
    {

        private string name{get;set;}
        public employee(string n)
        {
            name = n;
        }

        public event middleBoy.playGame game;
        public void iPlayGame()
        {
            if (game != null)
            {
                playGameEventArgs e=new playGameEventArgs();
                e.name = name;
                game(this,e);
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            employee ee = new employee("Javk");
            ee.game += new middleBoy.playGame(Boss.notify);
            ee.game += new middleBoy.playGame(Admin.notify);
            ee.iPlayGame();
            Console.ReadLine();
        }
    }
}

1.delegate做 监控人、事件发生者 之间的通讯人

2. 新的事件发生者的参数需要继承EventArgs,做成新的消息

3.事件发生者要判断事件是否为空再运行行动

4.多路发布遵守OPP原则(原基类封闭原则,开放业务类)

  //消息
    class playGameEventArgs:EventArgs
    {
        public string name{get;set;}

    }
    class Boss
    {
        public static void notify(object obj, playGameEventArgs e)
        {
            Console.WriteLine(e.name + " 玩游戏了");
        }
    }
    //管理人2
    class Admin
    {
        public static void notify(object obj, playGameEventArgs e)
        {
            Console.WriteLine(e.name + " 玩游戏了");
        }
    }
    class employee
    {

        private string name{get;set;}
        public employee(string n)
        {
            name = n;
        }
//用泛式代替了代理
        public event EventHandler<playGameEventArgs> game;
        public void iPlayGame()
        {
            if (game != null)
            {
                playGameEventArgs e=new playGameEventArgs();
                e.name = name;
                game(this,e);
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            employee ee = new employee("Javk");
            ee.game += Boss.notify;
            ee.game +=Admin.notify;
            ee.iPlayGame();
            Console.ReadLine();
        }
    }
}

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:asp.net MVC 学习笔记

下一篇:C#中Messagebox.Show()常用参数用法详解