c# action使用 事件 訂閱與發佈

//服務器
    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);
        }
    }
  1. static void Main()

  2. {Server s = new Server();Client c = new Client(s);s.Send("Hello");Console.ReadKey();

  3. }

這個用例很好

 

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("孩子 : 打完這局再喫。");
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章