看懂 ,學會 .NET 事件的正確姿式-簡單版

using System;
namespace EventTest
{
    public class EventDemo
    {
        public void EventTest()
        {
            Cat cat = new Cat();
            MouseEventArgs ms = new MouseEventArgs();
            MasterEventArgs mas = new MasterEventArgs();
            cat.Calling += ms.Escape;//老鼠對 clling 訂閱
            cat.Calling += mas.Wakened;//人 對 calling 訂閱
            cat.Call(); //貓叫
        }
    }
    public sealed class Cat
    {
        public event EventHandler Calling;
        public void Call()
        {
            Console.WriteLine("貓叫了...");
            Calling?.Invoke(this, EventArgs.Empty);
        }
    }
    public sealed class MouseEventArgs : EventArgs
    {
        public void Escape(object sender, EventArgs e)
        {
            Console.WriteLine("老鼠逃跑了...");
        }
    }
    public sealed class MasterEventArgs : EventArgs
    {
        public void Wakened(object sender, EventArgs e)
        {
            Console.WriteLine("主人醒了");
        }
    }
}
相關文章
相關標籤/搜索