Can I reverse the order of a multicast delegate event?

前端 未结 3 2164
耶瑟儿~
耶瑟儿~ 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:43

    Controlling When and If a Delegate Fires Within a Multicast Delegate

    The following method creates a multicast delegate called allInstances and then uses GetInvocationList to allow each delegate to be fired individually, in reverse order:

    public static void InvokeInReverse()
    {
        MyDelegate myDelegateInstance1 = new MyDelegate(TestInvoke.Method1);
        MyDelegate myDelegateInstance2 = new MyDelegate(TestInvoke.Method2);
        MyDelegate myDelegateInstance3 = new MyDelegate(TestInvoke.Method3);
    
        MyDelegate allInstances =
                myDelegateInstance1 +
                myDelegateInstance2 +
                myDelegateInstance3;
    
        Console.WriteLine("Fire delegates in reverse");
        Delegate[] delegateList = allInstances.GetInvocationList();
        for (int counter = delegateList.Length - 1; counter >= 0; counter--)
        {
            ((MyDelegate)delegateList[counter])();
        }
    }
    

提交回复
热议问题