using System; using System.Collections.Generic; using System.Text; //事件允許一個對象將方式的事件通知其他對象,將發生的事件通知其他的對象稱爲發行者,同時對象也可以訂閱事件,該對象 //稱爲訂閱者 namespace interfaceDemo { //事件處理分爲四步: //1、定義事件 //2、使用委託定義事件 //3、訂閱事件 //4、引發事件 //語法:[訪問修飾符] event 委託名 事件名 class EventTest { public delegate void MathOp(int i, int j);//定義委託 public event MathOp eventMath;//事件定義 static void Main(string[] args) { EventTest et = new EventTest();//對象實例化 et.eventMath += new MathOp(Add);//訂閱事件,實際上是添加一個指向方法的委託,當事件引發時將通過委託調用此方法,一個時間有多個訂閱者,即通過委託可以將多個方法添加到某個事件中 Console.WriteLine("請輸入兩個正數:"); int m = int.Parse(Console.ReadLine()); int n = int.Parse(Console.ReadLine()); if (m > 0 & n > 0)//滿足一定條件,引發事件 { et.eventMath(m, n); } Console.ReadLine(); } public static void Add(int i, int j) { Console.WriteLine("{0}+{1}={2}", i, j, i + j); } } }