Information Technology Reference
In-Depth Information
public void
AddMsg(
int
priority,
string
msg)
{
EventHandler
<
LoggerEventArgs
> l = log;
if
(l !=
null
)
l(
null
,
new
LoggerEventArgs
(priority, msg));
}
}
The C# compiler creates the add and remove accessors for the event. I find
the public event declaration language more concise and easier to read and
maintain than the add/remove syntax. When you create events in your
class, declare public events and let the compiler create the add and remove
properties for you. Writing your own add and remove handlers lets you do
more work in the add and remove handlers.
Events do not need to have any knowledge about the potential listeners.
The following class automatically routes all messages to the Standard Error
console:
class
ConsoleLogger
{
static
ConsoleLogger()
{
Logger
.Singleton.Log += (sender, msg) =>
{
Console
.Error.WriteLine(
"{0}:\t{1}"
,
msg.Priority.ToString(),
msg.Message);
};
}
}
Another class could direct output to the system event log:
class
EventLogger
{
private static
Logger
logger =
Logger
.Singleton;
private static string
eventSource;
private static
EventLog
logDest;
static
EventLogger()
{