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 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 EventHandler<CarEventArgs> d2 = new EventHandler<CarEventArgs>(SomeEvent2Handler); c.SomeEvent2 += d2; c.SomeMethod(); Console.ReadLine(); } public static void SomeEvent1Handler(string msg) { Console.WriteLine("SomeEvent1Handler " + msg); } public static void SomeEvent2Handler(object sender, CarEventArgs e) { if (sender is Car) { Car c = (Car)sender; Console.WriteLine("{0} says {1} ", sender, e.msg); } } } public class Car { public delegate void SomeDelegate(string msg); public delegate void SomeDelegate2(object sender, CarEventArgs e); public event SomeDelegate SomeEvent1; //public event SomeDelegate2 SomeEvent2; public event EventHandler<CarEventArgs> SomeEvent2; public void SomeMethod() { //some code if (SomeEvent1 != null) SomeEvent1("someMessage"); // fire Event Handler //some code if (SomeEvent2 != null) SomeEvent2(this, new CarEventArgs("someMessage2")); // fire Event Handler } } public class CarEventArgs : EventArgs { public readonly string msg; public CarEventArgs(string message) { msg = message; } } } |