个人理解c#的委托和事件,附带例子

来源:互联网 发布:php require__DIR__ 编辑:程序博客网 时间:2024/05/16 23:38
一个很简单的例子: 就是同学在寝室睡觉,委托班长,老师上课时给自己发消息!

所以流程就是:

1.注册消息:同学们告诉班长,要给我发消息(这就相当于在班长那里注册了一条委托消息)。

2.检测发送条件:班长检测到老师上课的消息。

3.发送消息:于是就给注册了消息通知的同学发消息。


using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace TestDelegate{    public delegate void DianMingDelegate(object sender, string str);    public class Student    {        public string Name;        public Student(string name)        {            Name = name;        }        public void ReciveMsg(object sender, string str)        {            Monster ms = sender as Monster;            Console.WriteLine(Name + " -- 收到" + ms.Name + "的消息:-->" + str);        }    }    public class Monster : Student    {        //public event DianMingDelegate Dmd;        private event DianMingDelegate _dmEvent;        private string _info;        public Monster(string name):base(name)        {        }        // 想要注册点名通知的人来我这里哦        public void Regist(DianMingDelegate d)        {            _dmEvent += d;        }        // 通知注册了的同学        private void Notify()        {            if(_dmEvent != null)            {                _dmEvent(this, _info);            }        }        public void CheckDm(LaoShi ls)        {            _info = "    " + ls.Name + ls.SpeakInfo;            Notify();        }    }    public class LaoShi : Student    {        public bool IsDm;        public string SpeakInfo;        public LaoShi(string name) : base(name)        {                    }        // 点名        public void Dm()        {            IsDm = true;            SpeakInfo = "说:今天要点名!";            Console.WriteLine(SpeakInfo);        }        public void Sk()        {            IsDm = false;            SpeakInfo = "说:今天就不点名了,直接上课!";            Console.WriteLine(Name + SpeakInfo);        }    }    public class TestEvent    {        public static void Main(string[] args)        {            Student s1 = new Student("小明");            Student s2 = new Student("小红");            Monster m1 = new Monster("班长");            // 这里点名事件设为public            // 向班长注册点名通知事件            //m1.Dmd += s1.ReciveBzMsg;            //m1.Dmd += s2.ReciveBzMsg;            //m1.Dmd += m1.ReciveBzMsg;            // 这里点名事件设为private            m1.Regist(s1.ReciveMsg);            m1.Regist(s2.ReciveMsg);            m1.Regist(m1.ReciveMsg);            LaoShi ls = new LaoShi("化学老师");            //ls.Dm();            ls.Sk();            m1.CheckDm(ls);            Console.ReadKey();        }            }}


如果有问题,请指出,谢谢!


原创粉丝点击