Event

using System;

namespace Event1
{
   class Me
    {
        private string _sender;
        public Me(string sender)
        {
            _sender = sender;
        }
        //1.定义委托
        public delegate void DinnerHandler(string name);
        //2.定义事件
        public event DinnerHandler dinnerEvent;
        //3.发布聚餐消息
        public void SendDinnerMsg(string msg)
        {
            if(dinnerEvent!=null)
            {
                dinnerEvent(msg+"(发件人"+_sender+")");
            }
        }
    }

    class Friend
    {
        private string _name;
        public Friend(string name)
        {
            _name = name;
        }
        public void ReceiveMsg(string msg)
        {
         
            Console.WriteLine(_name + "收到消息了,到时准时参加!"+"---------["+msg+"]");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Me me = new Me("atx");
            Friend f1 = new Friend("Adele");
            Friend f2 = new Friend("Tom");
            Friend f3 = new Friend("Taylor");

            me.dinnerEvent += new Me.DinnerHandler(f1.ReceiveMsg);
            me.dinnerEvent += new Me.DinnerHandler(f2.ReceiveMsg);
            me.dinnerEvent += new Me.DinnerHandler(f3.ReceiveMsg);

            me.SendDinnerMsg("朋友们,我们明天下午去聚餐");
        }
    }
}

Event_第1张图片

你可能感兴趣的:(C#)