static void Main(string[] args) { Car c1 = new Car("car1", 100, 10); int cnt = 0; // Register event handlers as anonymous methods c1.AboutToBlow += delegate { Console.WriteLine("Bout to blow, brah!"); }; c1.AboutToBlow += delegate(object sender, CarEventArgs e) { cnt++; Console.WriteLine("Message from Car: {0}", e.msg); }; c1.Exploded += delegate(object sender, CarEventArgs e) { Console.WriteLine("Fatal message from Car: {0}", e.msg); }; for (int i = 0; i < 6; i++) { c1.Accelerate(20); } // Unecessarily complex code SomeDelegate sd = delegate { Console.WriteLine("Called {0} times", cnt); }; sd.Invoke(); Console.ReadLine(); }
void UseAnonymousExpression() { // un named function assigned to SomeDelegate(); SomeDelegate del = () => Debug.Log("Anonymous Expression called."); del += NamedExpression; del.Invoke(); // Anonymous Expression called. // Named Expression called. }
private static void RunDelegate() { // 委派:可以將工作加入到某個等待被執行的委派當中,如下程式碼,在SomeDelegate method 代表method是一個委派可以加入相同參數的方法, // 如程式碼中的Method1、Method2、Method3,都是丟給method來執行。 Console.WriteLine("委派:可以將工作加入到某個等待被執行的委派當中,如下程式碼,在SomeDelegate method 代表method是一個委派可以加入相同參數的方法,如程式碼中的Method1、Method2、Method3,都是丟給method來執行。"); Console.WriteLine("Start (4) Run Delegate method"); SomeDelegate method = Method1; method += Method2; method += Method3; method.Invoke("HI"); Console.WriteLine("Done. 請按任意鍵繼續"); Console.ReadLine(); }
public void DelegateTest() { SomeDelegate method = new SomeDelegate(TestDelegateMethod); method.Invoke(3); }