123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnonymMethods { class Program { static void Main(string[] args) { int localInt = 123; SomeClass sc = new SomeClass(); sc.SetDelegate(SomeHandler); SomeClass.SomeDelegate d = new SomeClass.SomeDelegate(SomeEventHandler); sc.SomeEvent1 += d; // assigning anonymous methods with or without params sc.SomeEvent1 += delegate { Console.WriteLine("Anonymous method "); }; // << works without param - why? sc.SomeEvent1 += delegate(string msg) { Console.WriteLine("Anonymous method "+msg); }; sc.SomeEvent1 += delegate { Console.WriteLine("Anonymous method with local var "+localInt); }; // << works without param - why? // lambda expression - like alias for above examples sc.SomeEvent1 += (string msg) => { Console.WriteLine("Lambda expression " + msg); }; // start testing... sc.SomeDelegateMethod(); sc.SomeEventMethod(); Console.ReadLine(); } public static void SomeHandler(string Aparam) { Console.WriteLine(Aparam); } public static void SomeEventHandler(string Aparam) { Console.WriteLine(Aparam); } } class SomeClass { // delegate public delegate void SomeDelegate(string Aparam); private SomeDelegate listOfHandlers; public void SetDelegate(SomeDelegate method) { listOfHandlers += method; } //event public event SomeDelegate SomeEvent1; // firing methods public void SomeDelegateMethod() { if (listOfHandlers != null) { listOfHandlers("someDelegateMessage"); } } public void SomeEventMethod() { if (SomeEvent1 != null) { SomeEvent1("someEventMessage"); } } } } |