Good example
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Events2 { class Program { static void Main(string[] args) { Car c = new Car(); Car.SomeDelegate d = new Car.SomeDelegate(SomeEvent1Handler); c.SomeEvent1 += d; // added EventHandler c.SomeEvent1 -= d; // removed EventHandler Car.SomeDelegate d2 = new Car.SomeDelegate(SomeEvent2Handler); c.SomeEvent2 += d2; // added EventHandler // c.SomeEvent2 -= d2; // removed EventHandler //c.SomeEvent1 += new Car.SomeDelegate(SomeEvent1Handler); // another way to assign Event handler //c.SomeEvent2 += new Car.SomeDelegate(SomeEvent2Handler); c.SomeMethod(); Console.ReadLine(); } public static void SomeEvent1Handler(string msg) { Console.WriteLine("SomeEvent1Handler "+ msg); } public static void SomeEvent2Handler(string msg) { Console.WriteLine("SomeEvent2Handler "+ msg); } } public class Car { public delegate void SomeDelegate(string msg); public event SomeDelegate SomeEvent1; public event SomeDelegate SomeEvent2; public void SomeMethod() { //some code if (SomeEvent1 != null) SomeEvent1("someMessage"); // fire Event Handler //some code if (SomeEvent2 != null) SomeEvent2("someMessage2"); // fire Event Handler } } } |
Bad Example not Ok variant
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventsBadExample { class Program { static void Main(string[] args) { Car c = new Car(); c.listOfHandlers = new Car.SomeDelegate(SomeHandler); // assigned c.listOfHandlers = new Car.SomeDelegate(SomeHandler2); // re assigned, bad !!! c.Accelerate(10); c.listOfHandlers.Invoke("123"); // <<< direct call, bad !!! Console.ReadLine(); } static void SomeHandler(string message) { Console.WriteLine(message); } static void SomeHandler2(string message) { Console.WriteLine(message+ " 2"); } } public class Car { public delegate void SomeDelegate(string message); public SomeDelegate listOfHandlers; // <<< must be private !!! public void Accelerate(int delta) { if (listOfHandlers != null) listOfHandlers("some message"); } } } |