简体   繁体   中英

C# forward interface events

I have an interface defining an event:

interface IEXampleinterface 
{
   event MyEventHandler MyEvent;
}

In my GUI class I am calling a "processor" class which is again calling a "parser" class which implements the interface:

class GUI
{
   public DoSomething()
   {
      Processor processor = new Processor();
      processor.MyEvent += new MyEventHandler(processor_myevent);
      processor.DoSomething();
   }
   public processor_myevent(object sender, EventArgs e)
   {
      ...
   }
}

Processor class:

class processor
{
   IExampleInterface parser;
   event MyEventHandler MyEvent;

   public void DoSomething()
   {
      parser = new Parser();
      parser.MyEvent += new MyEventHandler(parser_myevent);
      parser.DoStuff();
   }
   public void parser_myevent(object sender, EventArgs e)
   {
      if(MyEvent != null)
      {
         MyEvent(sender, e)
      }
   }
}

Parser class:

class Parser : IExampleinterface
{
   event MyEventHandler MyEvent;

   public void DoStuff()
   {
      MyEvent(this, new EventArgs());
   }
}

As you can see, the "Processor" class just takes the event from "Parser" and forwards it to the GUI. This is totally working, but I was asking if there is a more elegant way of doing this kind of event forwarding.

Instead of creating a new event and pass events through, you could also point directly to that event:

public event MyEventHandler MyEvent
{
    add
    {
        parser.MyEvent += value;
    }
    remove
    {
        parser.MyEvent -= value;
    }
}

I am not sure if this is the prettiest thing to do, maybe you are better off with a better design. However, this will do the job until I have figured out a better way ;) .

First of all, doing MyEvent(sender, e) is considered "bad", the sender parameter should always be this so you know which event publisher raised the event. GUI has no reference to parser so it can't do any of the normal comparisons to tell which parser raised the event and this may break some UI frameworks that rely on the "standard" event pattern.

That being said, you can change how events are subscribed and unsubscribed to forward the subscription

class processor
{
   IExampleInterface parser;
   event MyEventHandler MyEvent
   {
      add { parser.MyEvent += value; }
      remove { parser.MyEvent -= value; }
   }

This gives the same behavior as MyEvent(sender, e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM