C # Delegate and event (2): Use EventArgs and EventHandler In the. Net Framework,
As mentioned in the previous article, events are associated through delegation, and delegation can contain various parameters, in which event parameters (EventArgs) can be used. At the same time, it can also be used. net Framework provides a delegate EventHandler to Handle the Le event.
Let's look at a scenario (this scenario is in the book): buy a car. The dealer (CarDealer) will go to the new car event, which will be subscribed by the buyer (Comsumer) and will be patronized once a new car comes out. Here, because detailed vehicle information is required, it is troublesome to use the method without parameters mentioned above. We need to redefine a delegate and event parameter (EventArgs ).
1. event parameters (CarInfoEventArgs)
Derived from EventArgs provided by. Net, attributes containing vehicle names
public class CarInfoEventArgs : EventArgs{ public string Car { get; private set; } public CarInfoEventArgs(string car) { this.Car = car; }}
2. Event (NewCarInfo)
Here we use the delegate EventHandler that comes with. Net to declare an event. Correspondingly, the event handler must use the parameter corresponding to the delegate to construct the event.
public event EventHandler<CarInfoEventArgs> NewCarInfo;
Note that this is a generic delegate. Here the parameter type is specified as CarInfoEventArgs. The EventHandler definition is as follows:
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs : EventArgs
We can see that this delegate contains two parameters: one object type and one generic parameter, and this generic parameter is limited to EventArgs or EventArgs-derived types.
3. Complete object
CarDealer
Public class CarDealer {public event EventHandler <CarInfoEventArgs> NewCarInfo; // trigger the event public void NewCar (string car) {Console. writeLine ($ "CarDealer, new car {car}"); if (NewCarInfo! = Null) {NewCarInfo (this, new CarInfoEventArgs (car ));}}}
Consumer
public class Consumer{ public string Name { get; private set; } public Consumer(string name) { this.Name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine($"{name}: car {e.Car} is new"); }}
4. Specific implementation
public class Program{ static void Main() { var dealer = new CarDealer(); var michael = new Consumer("Michael"); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar("Mercedes"); var nick = new Consumer("Nick"); dealer.NewCarInfo += nick.NewCarIsHere; dealer.NewCar("Ferrari"); dealer.NewCarInfo -= michael.NewCarIsHere; dealer.NewCar("Toyota"); }}
The execution result is as follows: