Forwarding events in C#

痴心易碎 提交于 2019-11-28 04:50:59
Jon Skeet

Absolutely:

class B
{
    private A m_a = new A();

    public event EventType EventB
    {
        add { m_a.EventA += value; }
        remove { m_a.EventA -= value; }
    }
}

In other words, the EventB subscription/unsubscription code just passes the subscription/unsubscription requests on to EventA.

Note that this doesn't allow you to raise the event just for subscribers who subscribed to EventB, however. It's like passing someone's address directly onto a mass marketing company, whereas your original way is more like subscribing to the mass marketing company yourself, and allowing people to ask you to send copies of the mails to them.

IMO, your original code is (more or less) correct. In particular, it allows you to provide the correct sender (which should be the B instance for people who think they are subscribing to an event on B).

There are some tricks to reduce the overheads at runtime if the event isn't subscribed, but this adds more code:

class B {
   A m_A = new A();
   private EventType eventB;
   public event EventType EventB {
       add { // only subscribe when we have a subscriber ourselves
           bool first = eventB == null;
           eventB += value;
           if(first && eventB != null) m_A.EventA += OnEventB;
       }
       remove { // unsubscribe if we have no more subscribers
           eventB -= value;
           if(eventB == null) m_A.EventA -= OnEventB;
       }
   }

   protected void OnEventB(object sender, EventArgsType args) {
      eventB?.Invoke(this, args); // note "this", not "sender"

   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!