using System; using System.Collections.Generic; using System.Text; //多重傳送事件 namespace interfaceDemo { //多重傳送事件是指一個事件同時有多個訂閱者,即通過委託將多個方法添加到該事件中,當事件被引發時,同時 //觸發這些委託的執行 class MutiplyEventTest { public delegate void MathOp(int i, int j);//定義委託 public event MathOp eventMath;//事件定義 static void Main(string[] args) { MutiplyEventTest et = new MutiplyEventTest();//對象實例化 //四個執行不同的方法的委託訂閱同一個事件 et.eventMath += new MathOp(Add);//訂閱事件,實際上是添加一個指向方法的委託,當事件引發時將通過委託調用此方法,一個時間有多個訂閱者,即通過委託可以將多個方法添加到某個事件中 et.eventMath += new MathOp(Minus); et.eventMath += new MathOp(Mutiply); et.eventMath += new MathOp(Divide); 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); } public static void Minus(int i, int j) { Console.WriteLine("{0}-{1}={2}", i, j, i - j); } public static void Mutiply(int i, int j) { Console.WriteLine("{0}*{1}={2}", i, j, i * j); } public static void Divide(int i, int j) { Console.WriteLine("{0}/{1}={2}", i, j, i / j); } } }