namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Publisher pub = new Publisher(); Subscriber sub = new Subscriber(); pub.NumberChanged += new NumberChangedEventHandler(sub.OnNumberChanged); pub.DoSomething(); pub.NumberChanged(100); Console.Read(); } } public delegate void NumberChangedEventHandler (int count); public class Publisher { private int count; public NumberChangedEventHandler NumberChanged; public void DoSomething() { if (NumberChanged != null) { count++; NumberChanged(count); } } } public class Subscriber { public void OnNumberChanged(int count) { Console.WriteLine("Subscriber notified: count = {0}", count); } }}
当使用委托变量时,客户端可以直接通过委托变量触发事件,也就是直接调用pub.NumberChanged(100),这将会影响所有注册了该委托的订阅者。而事件的本意应该为事件发布者在其本身某个行为中触发,比如在DoSomething()中满足某个条件后触发。通过添加event关键字来发布事件,事件发布者的封装性会更好,事件仅仅供其他类型订阅,而客户端不能直接直接触发事件,事件只能在事件发布者Publisher类的内部触发。
public event NumberChangedEventHandler NumberChanged;