How do I get the subscribers of an event?

前端 未结 4 2075
一个人的身影
一个人的身影 2020-11-29 08:17

I need to copy the subscribers of one event to another event. Can I get the subscribers of an event (like MyEvent[0] returning a delegate)?

If this is not possible I

4条回答
  •  死守一世寂寞
    2020-11-29 08:38

    C# events/delegates are multicast, so the delegate is itself a list. From within the class, to get individual callers, you can use:

    if (field != null) 
    { 
        // or the event-name for field-like events
        // or your own event-type in place of EventHandler
        foreach(EventHandler subscriber in field.GetInvocationList())
        {
            // etc
        }
    }
    

    However, to assign all at once, just use += or direct assignment:

    SomeType other = ...
    other.SomeEvent += localEvent;
    

提交回复
热议问题