C # Use of events (1)

Source: Internet
Author: User

====================
@ Define an event in the class
====================

Using system;

// Mail management.
Class mailmanager {
// 1. Define the event parameters to send additional information to the event receiver.
// The Event parameter classes should all inherit from system. eventargs and end with eventargs.
Public class mailmsgeventargs: eventargs {
Public mailmsgeventargs (string from, string to, string subject, string body ){
This. From = from; // the sender.
This. To = to; // recipient.
This. Subject = subject; // topic.
This. Body = body; // body.
}
Public readonly string from, to, subject, body;
}

// 2. Define a delegate type to specify the method prototype called when an event is triggered.
// The Name Of The delegate type should end with eventhandler. In addition, the return value of the method prototype should be void, and there are two parameters:
// The first parameter points to the notification sending object, and the second parameter is the event parameter. If the defined time does not need to be passed to the event Receiver
// Additional information, you do not need to define a new delegate type, directly use system. eventhandler, and set eventargs. Empty
// Pass it to the second parameter.
Public Delegate void mailmsgeventhandler (Object sender, mailmsgeventargs ARGs );

// 3. Define events.
// The event name defined below is mailmsg and its type is mailmsgeventhandler. It means that all event recipients must provide
// A method that matches the prototype with mailmsgeventhandler.
Public event mailmsgeventhandler mailmsg;

// 4. Trigger the event. Convert some external inputs into the action that triggers the event.
Public void simulatearrivingmsg (string from, string to, string subject, string body ){
Mailmsgeventargs E = new mailmsgeventargs (from, to, subject, body );

// Call the virtual method to notify the object that the event has occurred. If the derived type does not overwrite the virtual method,
// The object notifies the listener of all registration times.
Onmailmsg (E );
}

// 5. Handle the event and notify the event listener.
Protected virtual void onmailmsg (mailmsgeventargs e ){
If (mailmsg! = NULL ){
// Notify the event to all objects on the delegated linked list.
Mailmsg (this, e );
}
}
}

 

======================================
@ Compiler processing of event definition statements
======================================

For the statements defining events in the code above:
Public event mailmsgeventhandler mailmsg;
The compiler translates it into the following three methods:

// 1. A "private" delegate type field initialized to null.
Private mailmsgeventhandler mailmsg = NULL;
// 2. a "public" Add _ * method that allows other objects to register events.
[Methodimplattritions (methodimploptions. Synchronized)]
Public void add_mailmsg (mailmsgeventhandler handler ){
This. mailmsg = (mailmsgeventhandler) Delegate. Combine (mailmsg, Handler );
}
// 3. a "public" Remove _ * method that allows other objects to log out of an event.
[Methodimplattritions (methodimploptions. sysnchronized)]
Public void remove_mailmsg (mailmsgeventhandler handler ){
Mailmsg = (mailmsgeventhandler). Delegate. Remove (mailmsg, Handler );
}

 

The Add _ * and remove _ * methods both apply the methodimplattribute feature. These methods are identified as synchronous methods so that they can
Thread security: Multiple Event Listeners can register or cancel events at the same time without damaging the delegate linked list. Access restrictions for these two methods
Depending on the access restriction of the event, if the event is defined as a protected event, the two methods will also be protected.

================
@ Define the class for listening events
================

// The fax machine listens on mailmsg events of mailmanager and sends a fax (output to the console ).
Class Fax
{
// Pass the mailmanager object to the constructor.
Public Fax (mailmanager mm ){
// Construct a mailmsgeventhandler delegate instance pointing to the faxmsg callback method,
// Register the mailmsg event of mailmanager.
Mm. mailmsg + = new mailmanager. mailmsgeventhandler (faxmsg );
}

// Mailmanager will call this method to notify the fax object to receive a new email message.
// Sender: indicates the mailmanager object. If you want to communicate with the event trigger, you can use this parameter.
// E: additional event information provided by the mailmanager object.
Private void faxmsg (Object sender, mailmanager. mailmsgeventargs e ){
Console. writeline ("from: {0} \ n to: {1} \ n subject: {2} \ n body: {3} \ n" +
E. From, E. To, E. Subject, E. Body );
}

// Deregister the event.
Public void unregister (mailmanager mm ){
// Create a new delegated instance to remove it from the delegated linked list (see Delegation for more information)
Mailmanager. mailmsgeventhandler callback = new mailmanager. mailmsgeventhandler (faxmsg );
Mm. mailmsg-= callback;
}
}

 

==========
@ Use event
==========

Using system;

Public class test
{
Public static void main (string [] ARGs ){
// Define the event sender mm.
Mailmanager Mm = new mailmanager ();

// Defines the time at which the event listener listens to mm.
Fax = new fax (mm );

// Trigger the event defined by the event sender.
Mm. simulatearrivingmsg ("me", "you", "love", "I love you! ");
}
}

Output:
From: Me
To: You
Subject: Love
Body: I love you!

 

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.