C#事件订阅及触发例子
最典型的事件例子,猫叫了(事件源),老鼠跑了(事件订阅者),惊醒主人(事件订阅者)
源代码:
class Program { static void Main(string[] args) { Cat cat = new Cat(); cat.catEvent += Mouse;//订阅猫事件 cat.catEvent += Person;//订阅人事件 cat.Cry("猫:喵~");//猫叫的动作,触发事件 Console.ReadKey(); } private static void Person(object sender, EventArgs e) { Console.WriteLine("人:大半夜的不睡觉,叫唤个啥呢?~"); } private static void Mouse(object sender, EventArgs e) { Console.WriteLine("猫:快跑~"); } } public class Cat { public event EventHandler<EventArgs> catEvent; public void Cry(string msg) { Console.WriteLine(msg); catEvent(this, new EventArgs()); } }
执行结果: