C# 事件 订阅与发布

两种方式:

一:

//服务器
    public class Server
    {
        //服务器发布的事件
        public event Action<string> MyEvent;
        public void Send(string msg)
        {
            if (MyEvent != null)
            {
                Console.WriteLine("Server推送消息:" + msg);
                MyEvent(msg);
            }
        }
    }

    //客户端
    public class Client
    {
        public Client(Server s)
        {
            //客户端订阅
            s.MyEvent += Receive;
        }

        public void Receive(string msg)
        {
            Console.WriteLine("Client收到了通知:" + msg);
        }
    }


调用:

static void Main()
        {
            Server s = new Server();
            Client c = new Client(s);
            s.Send("Hello");

            Console.ReadKey();
        }






二:转载:https://www.cnblogs.com/David-Huang/p/5150671.html

class Program
    {
        public static void Main(string[] args)
        {
            //实例化对象
            Mom mom = new Mom();
            Dad dad = new Dad();
            Child child = new Child();
            
            //将爸爸和孩子的Eat方法注册到妈妈的Eat事件
            //订阅妈妈开饭的消息
            mom.Eat += dad.Eat;
            mom.Eat += child.Eat;
            
            //调用妈妈的Cook事件
            mom.Cook();
            
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
    
    public class Mom
    {
        //定义Eat事件,用于发布吃饭消息
        public event Action Eat;
        
        public void Cook()
        {
            Console.WriteLine("妈妈 : 饭好了");
            //饭好了,发布吃饭消息
            Eat?.Invoke();
        }
    }
    
    public class Dad
    {
        public void Eat()
        {
            //爸爸去吃饭
            Console.WriteLine("爸爸 : 吃饭了。");
        }
    }
    
    public class Child
    {
        public void Eat()
        {
            //熊孩子LOL呢,打完再吃
            Console.WriteLine("孩子 : 打完这局再吃。");
        }
    }


原文地址:https://www.cnblogs.com/hanjun0612/p/9779783.html