C# 自定义事件

 1  public class CarInfoEventArgs : EventArgs
 2     {
 3         public string Car { get; set; }
 4         public CarInfoEventArgs(string car)
 5         {
 6             this.Car = car;
 7         }
 8     }
 9     
10     public class CarDealer
11     {
12         public event EventHandler<CarInfoEventArgs> NewCarInfo;
13         
14         public void NewCar(string car)
15         {
16             Console.WriteLine("CarDealer,new car {0}", car);
17             RaiseNewCarInfo(car);
18         }
19         protected virtual void RaiseNewCarInfo(string car)
20         {
21             EventHandler<CarInfoEventArgs> newCarInfo = NewCarInfo;
22             if (newCarInfo != null)
23                 newCarInfo(this, new CarInfoEventArgs(car));
24         }
25     }
 1  public class Consumer
 2     {
 3        private string name;
 4        public Consumer(string name)
 5        {
 6            this.name = name;
 7        }
 8        public void NewCarIsHere(object sender,CarInfoEventArgs e)
 9        {
10            Console.WriteLine("{0}: car {1} is new", name, e.Car);
11        }
12     }
 1  var dealer = new CarDealer();
 2 
 3             var michael = new Consumer("Michael");
 4             dealer.NewCarInfo += michael.NewCarIsHere;
 5 
 6             dealer.NewCar("Ferrari");
 7 
 8             var nick = new Consumer("Sebastian");
 9             dealer.NewCarInfo += nick.NewCarIsHere;
10 
11             dealer.NewCar("Mercedes");
12 
13             dealer.NewCarInfo -= michael.NewCarIsHere;
14 
15             dealer.NewCar("Red Bull Racing");

 

posted @ 2016-10-14 13:45  指间的徘徊  阅读(183)  评论(0编辑  收藏  举报