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

一个很简单的例子: 就是同学在寝室睡觉,委托班长,老师上课时给自己发消息!

所以流程就是:

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();
        }
        
    }
}


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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值