Forwarding events in C#

前端 未结 2 1599
难免孤独
难免孤独 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:44

    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.

提交回复
热议问题