• 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");
  • 相关阅读:
    MySQL索引
    《深度探索C++对象模型》笔记——Data语意学
    《深度探索C++对象模型》笔记——Function语意学
    近期的bug常见[从以前的零散笔记中整理]
    一个小trick
    3月9日-日记
    第一次考试_心得
    第一次考试_笔记
    哈希笔记
    Dp刷版笔记
  • 原文地址:https://www.cnblogs.com/farmer-y/p/5960134.html
Copyright © 2020-2023  润新知