C#事件-1
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 8 namespace Wrox.ProCSharp.Delegates 9 { 10 public class CarInfoEventArgs:EventArgs 11 { 12 public CarInfoEventArgs(string car) 13 { 14 this.Car = car; 15 } 16 17 public string Car {get; private set;} 18 } 19 20 public class CarDealer 21 { 22 public event EventHandler<CarInfoEventArgs> NewCarInfo; //泛型委托,约定:第一个参数是一个对象,包含事件的发送者,第二个参数提供了事件的相关信息 23 24 public void NewCar(string car) 25 { 26 Console.WriteLine("CarDealer, new car{0}", car);//显示car信息 27 28 RaiseNewCarInfo(car); 29 } 30 31 protected virtual void RaiseNewCarInfo(string car) 32 { 33 EventHandler<CarInfoEventArgs> newCarInfo = NewCarInfo; 34 if (newCarInfo != null) 35 { 36 newCarInfo(this, new CarInfoEventArgs(car)); 37 } 38 } 39 } 40 } 41 42 /////////////////////////////////////////////////////////////////////////////////// 43 44 private delegate EventHandler<CarInfoEventArgs> newCarInfo; 45 public event EventHandler<CarInfoEventArgs> NewCarInfo 46 { 47 add 48 { 49 newCarInfo += value; 50 } 51 remove 52 { 53 newCarInfo -= value; 54 } 55 } 56 57 //////////////////////////////////////////////////////////////////////// 58 59 using System; 60 61 namespace Wrox.ProCSharp.Delegates 62 { 63 public class Consumer 64 { 65 private string name; 66 67 public Consumer(string name) 68 { 69 this.name = name; 70 } 71 72 public void NewCarIsHere(object sender, CarInfoEventArgs e) 73 { 74 Console.WriteLine("{0}: car {1} is new", name, e.Car); 75 } 76 } 77 } 78 79 //////////////////////////////////////////////////////////////////////// 80 81 namespace Wrox.ProCSharp.Delegates 82 { 83 class Program 84 { 85 static void Main() 86 { 87 var dealer = new CarDealer(); 88 89 var michael = new Consumer("Michael"); 90 dealer.NewCarInfo += michael.NewCarIsHere; 91 92 dealer.NewCar("Ferrari"); 93 94 var sebastian = new Consumer("Sebastian"); 95 dealer.NewCarInfo += sebastian.NewCarInfo; 96 97 dealer.NewCar("Mercedes"); 98 99 dealer.NewCarInfo -=michael.NewCarIsHere; 100 101 dealer.NewCar("Red Bull Racing"); 102 } 103 } 104 }