开发者

Is it possible to "chain" EventHandlers in c#?

Is is possible to delegate events from inner object instance to corrent object's event handlers with a syntax like this:

public class MyControl {
   public event EventHandler Finish;

   private Wizard wizard;
   public MyControl( Wizard wizard ) {
      this.wizard = wizard;

      // some other initialization going on here...

      // THIS is what I want to do to chain events
      this.wizard.Finish += 开发者_如何学CFinish;
   } 
}

The motivation for the above structure is that I have many wizard-like UI flows and wanted to separate the Back, Forward & Cancel handling to a single class to respect Open Closed Principle and Single Responsibility Principle in my design.

Adding a method OnFinish and doing the normal checking there is always possible but on case there are lot's of nested events, it's going to end up with lot's of boilerplate code.


Two options. First:

 public event EventHandler Finish
 {
     add { wizard.Finish += value; }
     remove { wizard.Finish -= value; }
 }

Second, as you mentioned:

 public event EventHandler Finish;

 wizard.Finish += WizardFinished;

 private void WizardFinished(object sender, EventArgs e)
 {
     EventHandler handler = Finish;
     if (handler != null)
     {
         handler(this, e);
     }
 }

The benefit of the second form is that the source of the event then appears to be the intermediate class, not the wizard - which is reasonable as that's what the handlers have subscribed to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜