C#的委託和事件
阿新 • • 發佈:2018-11-19
委託
委託相當於C++的函式指標或者函式的引用。
using System; public class FunClass { public void func1() { Console.WriteLine ("func 1"); } public void func2() { Console.WriteLine ("func 2"); } } public class Test { public delegate void TestFunc(); public static void func3() { Console.WriteLine ("func 3"); } public static void Main() { FunClass funClass = new FunClass (); TestFunc testFunc1 = new TestFunc (funClass.func1); TestFunc testFunc2 = new TestFunc (funClass.func2); TestFunc testFunc3 = new TestFunc (func3); testFunc1 (); testFunc2 (); testFunc3 (); Console.ReadKey (); } }
事件
C#典型的觀察者模式,需要藉助於委託實現。先宣告一個委託型別,用於說明註冊事件的型別,然後再對觀察者的事件進行註冊,呼叫時說明。
Sender相當於事件的發出者,Receiver相當於觀察者。
using System; public class Sender { public delegate void SendMsg(); public event SendMsg sendEvent; public void Send() { if (sendEvent == null) { Console.WriteLine ("No Event"); Console.ReadKey (); } else { sendEvent (); Console.ReadKey (); } } } public class Receiver1 { public void recMsg() { Console.WriteLine ("recMsg 1 !"); } } public class Recevier2 { public void recMsg() { Console.WriteLine ("recMsg 2 !"); } } public class Test { public static void Main() { Sender sender = new Sender (); sender.Send (); Receiver1 receiver1 = new Receiver1 (); Recevier2 receiver2 = new Recevier2 (); sender.sendEvent += new Sender.SendMsg (receiver1.recMsg); sender.sendEvent += new Sender.SendMsg (receiver2.recMsg); sender.Send (); } }