Use event and delegate in subclass
Events may only be invoked from the class that declares them.
From outside of the definition of a class (even in a derived class) you can only register and unregister from an event
. Inside of the class, the compiler only allows you to raise the event. This is a by-design behavior of C# (which actually changes slightly in C#4 - Chris Burrows describes the changes on his blog).
What you want to do here is provide a RaiseLogEvent()
method in the base class, which would allow the derived class to invoke this event.
public abstract class Base
{
public delegate void logEvent(String message, int level);
public event logEvent log;
protected void RaiseLogEvent( string msg, int level )
{
// note the idomatic use of the copy/test/invoke pattern...
logEvent evt = log;
if( evt != null )
{
evt( msg, level );
}
}
}
As an aside, you should consider using the EventHandler<>
delegate type, rather than creating your own event types when possible.
Because events can only be called from the declaring class. Just create a method in the base class to call it:
protected virtual RaiseLogEvent(string s, int i)
{
log(s, i);
}
So you can use it in deriving classes, and even override it.
On another note, I would strongly advise you to follow the design guidelines for events, and create an own EventArgs class, and use the EventHandler<T>
delegate.