Event事件
语法代码
class Program { static void Main(string[] args) { var e = new EventTest(5); e.SetValue(100); e.ChangeNum += new EventTest.NumDelegate(EventTest.EventFired); e.SetValue(100); e.SetValue(200); Console.ReadLine(); } } class EventTest { private int value; public delegate void NumDelegate(); public event NumDelegate ChangeNum; public EventTest(int num) { SetValue(num); } public void SetValue(int Num) { if (value != Num) { value = Num; OnNumChanged(); } else { Console.WriteLine("没改变"); } } public static void EventFired() { Console.WriteLine("绑定了"); } protected virtual void OnNumChanged() { if (ChangeNum != null) { ChangeNum(); } else { Console.WriteLine("没绑定"); } } }
加event 关键字后
只能进行 += 或 -=操作,而不能=操作