EventHandler <TEventArgs> is defined as follows:
Public delegate void EventHandler <TEventArgs> (object sender, TEventArgs e) where TEventArgs: EventArgs
The first parameter must be of the object type (an object that contains the event sender)
The second parameter is of the T type (generic type). It defines a T Constraint and must be derived from the base class EventArgs.
CardInfoEventArgs is derived from the base class EventArgs
----------- Example ---------------
# Region Test Event 1
// EventArgs class
Public class CardInfoEventArgs: EventArgs
{
Public string Car {get; private set ;}
Public CardInfoEventArgs (string car)
{
This. Car = car;
}
}
// The class that triggers the event
Public class CarDealer
{
Public event EventHandler <CardInfoEventArgs> NewCardInfo;
Public void NewCar (string car)
{
Console. WriteLine ("CarDealer, new car {0}", car );
// Before triggering an event, check whether the entrusted NewCardInfo is not empty. If there is no subscription handler, the delegate is empty.
If (NewCardInfo! = Null)
{
NewCardInfo (this, new CardInfoEventArgs (car ));
}
}
}
// Event handling class
Public class Consumer
{
Private string name;
Public Consumer (string name)
{
This. name = name;
}
// Event handling method
Public void NewCarIsHere (object sender, CardInfoEventArgs e)
{
Console. WriteLine ("{0}: car {1} is new", name, e. Car );
}
}
# Endregion
Private void button _ Test Event upload click (object sender, EventArgs e)
{
CarDealer dealer = new CarDealer ();
Consumer michael = new Consumer ("Michael ");
Dealer. NewCardInfo + = michael. NewCarIsHere; // subscribe to events
Dealer. NewCar ("BMW ");
Consumer nick = new Consumer ("Nick ");
Dealer. NewCardInfo + = nick. NewCarIsHere; // subscribe to an event
Dealer. NewCar ("Benz ");
Dealer. NewCardInfo-= michael. NewCarIsHere; // cancels the subscription event.
Dealer. NewCar ("Audi ");
}
----- Test result -------