C # event mechanism memo

Source: Internet
Author: User

In C #, an event is essentially a restricted delegate. The following sample code can be used to illustrate this point:

The advantage of doing so is that you can change the response function at any time when an event occurs without modifying any code of the event class. when an event occurs, the function executed is bound at runtime.

 

Class Program
{
Static void main (string [] ARGs)
{
Alerteq AE = new alerteq ();
// Bind the Event Response Function
AE. Action + = new alerteq. actioneventhandler (eventhander. process );
// Event
AE. Action ("Sichuan", 6 );
AE. Action ("Sichuan", 5 );
AE. Action ("Sichuan", 3 );
}

}
// For earthquake events, action is the function of event occurrence.
Class alerteq
{

// Define the delegate
Public Delegate void actioneventhandler (Object o, earthquackargs E );

// Declare the event
Public event actioneventhandler action;

// Event occurred
Public void action (string area, int rank)
{
Earthquackargs Arg = new earthquackargs (area, rank );
Action (this, ARG );
}
}
// Capture earthquake events and handle real events
Static class eventhander
{
Public static void process (Object sender, earthquackargs message)
{
Console. writeline (sender. tostring () + "make the alert ;");
Console. writeline ("we have a" + message. Rank + "rank earthquack" + "in" + message. Area + "province! ");
}

}

// Event parameter class
Public class earthquackargs: eventargs
{
Public String area;
Public int rank;
Public earthquackargs (string area, int rank)
: Base ()
{
This. Area = area;
This. Rank = rank;
}
}

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.