我可以颠倒多播委托事件的顺序吗? [英] Can I reverse the order of a multicast delegate event?

查看:102
本文介绍了我可以颠倒多播委托事件的顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您订阅.NET中的事件时,订阅将添加到多播代理。当事件被触发时,代理人按照订阅的顺序进行调用。

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.

我想以某种方式覆盖订阅,因此订阅实际上是在反向订单。可以这样做吗?如何?

I'd like to override the subscription somehow, so that the subscriptions are actually fired in the reverse order. Can this be done, and how?

我认为这样的事情可能是我需要的:

I think something like this might be what I need?:

public event MyReversedEvent
{
    add { /* magic! */ }
    remove { /* magic! */ }
}


推荐答案

一个/rel =nofollow noreferrer>控制何时和如果代理在多播代理中触发

Controlling When and If a Delegate Fires Within a Multicast Delegate

以下方法创建一个多播代理名为allInstances,然后使用GetInvocationList来允许每个委托单独触发,按照相反的顺序:

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])();
    }
}

这篇关于我可以颠倒多播委托事件的顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆