Can I reverse the order of a multicast delegate event?

前端 未结 3 2112
耶瑟儿~
耶瑟儿~ 2021-02-19 19:21

When you subscribe to an event in .NET, the subscription is added to a multicast delegate. When the event is fired, the delegates are called in the order they were subscribed.<

3条回答
  •  梦谈多话
    2021-02-19 19:48

    You don't need any magic; you just need to reverse the addition.
    Writing delegate1 + delegate2 returns a new delegate containing the method(s) in delegate1 followed by the methods in delegate2.

    For example:

    private EventHandler myReversedEventField;
    public event EventHandler MyReversedEvent
    {
        add { myReversedEventField = value + myReversedEventField; }
        remove { myReversedEventField -= value; }
    }
    

    You don't need any magic in the remove handler, unless you want to remove the last occurrence of that handler instead of the first. (In case the same handler was added twice)

提交回复
热议问题