Forwarding events in C#

前端 未结 2 1597
难免孤独
难免孤独 2020-12-08 02:14

I\'m using a class that forwards events in C#. I was wondering if there\'s a way of doing it that requires less code overhead.

Here\'s an example of what I have so f

2条回答
  •  误落风尘
    2020-12-08 02:27

    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"
    
       }
    }
    

提交回复
热议问题