Effective C # Principle 22: Defining an external interface with events

Source: Internet
Author: User

You can use events to define some external interfaces for your type. The event is based on a delegate because the delegate can provide type-safe function signatures to the event handle. Plus most of the delegates ' examples are illustrated with events, so that developers initially assume that delegates and events are one thing. In principle 21, I have shown some examples of the use of delegates not on events. In order to complete their behavior, you must raise an event when your type communicates with many other customers.

As a simple example, you're doing a log class that publishes all the messages in your application like an information publisher. It accepts all messages posted from the program source and publishes the messages to interested audiences. These listeners can be consoles, databases, system logs, or other mechanisms. You can define a class like the one below that raises an event when a message arrives:

public class Loggereventargs:eventargs
{
Public readonly string message;
public ReadOnly int Priority;   
Public Loggereventargs (int p, string m)
{
Priority = p;
message = m;
}

///Define the signature for the event handler:
Public delegate void Addmessageeventhandler (object s Ender,
Loggereventargs msg);  
public class Logger
{
static Logger ()
{
_theonly = new Logger ();
 
Private Logger ()
{
}
private static Logger _theonly = null;
  Public Logger Singleton
{
Get
{
return _theonly;
 
}
//Define the event:
public event Addmessageeventhandler Log;
Add a message, and log it.   
public void addmsg (int priority, string msg)
{
///This idiom discussed below.
Addmessageeventhandler L = Log;  
if (l!= null)
L (NULL, new Loggereventargs (priority, MSG);
}
}

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.