《C#高级编程》事件的示例代码
运行结果:
Program.cs
1 using System; 2 3 namespace Wrox.ProCSharp.Delegates 4 { 5 class Program 6 { 7 static void Main() 8 { 9 var dealer = new CarDealer(); 10 11 var michael = new Consumer("Michael"); 12 dealer.NewCarInfo += michael.NewCarIsHere; 13 14 dealer.NewCar("Mercedes"); 15 16 var nick = new Consumer("Nick"); 17 dealer.NewCarInfo += nick.NewCarIsHere; 18 19 dealer.NewCar("Ferrari"); 20 21 dealer.NewCarInfo -= michael.NewCarIsHere; 22 23 dealer.NewCar("Toyota"); 24 25 Console.Read(); 26 } 27 } 28 }
CarDealer.cs
1 using System; 2 3 namespace Wrox.ProCSharp.Delegates 4 { 5 public class CarInfoEventArgs : EventArgs 6 { 7 public CarInfoEventArgs(string car) 8 { 9 this.Car = car; 10 } 11 12 public string Car { get; private set; } 13 } 14 15 public class CarDealer 16 { 17 public event EventHandler<CarInfoEventArgs> NewCarInfo; 18 19 public void NewCar(string car) 20 { 21 Console.WriteLine("CarDealer, new car {0}", car); 22 if (NewCarInfo != null) 23 { 24 NewCarInfo(this, new CarInfoEventArgs(car)); 25 } 26 } 27 } 28 }
Consumer.cs
1 using System; 2 3 namespace Wrox.ProCSharp.Delegates 4 { 5 public class Consumer 6 { 7 private string name; 8 9 public Consumer(string name) 10 { 11 this.name = name; 12 } 13 14 public void NewCarIsHere(object sender, CarInfoEventArgs e) 15 { 16 Console.WriteLine("{0}: car {1} is new", name, e.Car); 17 } 18 } 19 }