C # simple event example

Source: Internet
Author: User

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 -------

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.