Use event and delegate in subclass

Why can't I use the event declared in Base from Sub?

class Program
{
    static void Main(string[] args)
    {
        Sub sub = new Sub();
        sub.log += new Base.logEvent(sub_log);
        sub.go();
    }

    static void sub_log(string message, int level)
    {
        Console.Out.WriteLine(message + " " + level);
    }
}

public abstract class Base
{
    public delegate void logEvent(String message, int level);

    public event logEvent log;
}

public class Sub : Base
{

    public void go()
    {
        log("Test", 1); // <-- this wont compile
    }
}
+5
source share
3 answers

Events can only be called from a class that declares them.

Due to the class definition (even in a derived class), you can only register and unregister with event. Inside the class, the compiler only allows raising an event. This is C #'s behavioral behavior (which actually changes a bit in C # 4 - Chris Burroughs describes the changes on his blog ).

What you want to do is provide a method RaiseLogEvent()in the base class that will allow the derived class to raise 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 );
      }
  }
} 

EventHandler<>, , .

+6

. :

protected virtual RaiseLogEvent(string s, int i)
{
  log(s, i);
}

, .

EventArgs EventHandler<T>.

+2

, , .

. , .

Read the standard way to declare events in the base class so that they can also be raised from derived classes:

Raise base class events in derived classes

0
source

All Articles