事件,自己创建委托例子

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

namespace ConsoleApplication1
{
    public class BossDemo
    {
        public delegate void BossDelegete(string msg);  //定义委托
        public event BossDelegete BossEvent; //定义BossDelete委托类型的事件

        public void Onmsg(string msg)
        {
            if (BossEvent != null)  //判断是否绑定了事件处理方法
            {
BossEvent(msg); } } static void Main(string [] args) { BossDemo b = new BossDemo(); Worker w1 = new Worker("1"); Worker w2= new Worker("2"); b.BossEvent += new BossDelegete(w1.SendMessage); 使用+=事件订阅. b.BossEvent += new BossDelegete(w2.SendMessage); b.Onmsg("朋友你好今晚上加班"); Console.WriteLine("---------------------------"); Console.ReadKey(); } } public class Worker { private string workerId; public Worker(string wi) { this.workerId = wi; }
//事件处理函数,该函数符合委托的定义 public void SendMessage(string msg) { Console.WriteLine(msg); Console.WriteLine(this.workerId + "卧槽又加班"); Console.Read(); } } }

  

posted @ 2017-11-07 14:15  公众号python学习开发  阅读(306)  评论(0编辑  收藏  举报