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

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

问题描述

当你订阅的.NET事件,订阅添加到多播委托。当事件被触发时,代表们称为他们认购的顺序。



我想以某种方式覆盖认购,从而使订阅的烧制实际在逆转订单。可以这样做,以及如何



我觉得这样的事情可能是我所需要的:??



 公共事件MyReversedEvent 
{
加{/ *魔法! * /}
拆下{/ *魔法! * /}
}


解决方案

控制何时如果委托大火在一个多播委托 搜索



下面的方法创建一个多播委托叫allInstances,然后使用GetInvocationList,让每位代表进行单独发射,以相反的顺序:

 公共静态无效InvokeInReverse( )
{
MyDelegate myDelegateInstance1 =新的MyDelegate(TestInvoke.Method1);
MyDelegate myDelegateInstance2 =新的MyDelegate(TestInvoke.Method2);
MyDelegate myDelegateInstance3 =新的MyDelegate(TestInvoke.Method3);

MyDelegate allInstances =
myDelegateInstance1 +
myDelegateInstance2 +
myDelegateInstance3;

Console.WriteLine(逆火代表);
代表[] = delegateList allInstances.GetInvocationList();
为(INT计数器= delegateList.Length - 1;计数器> = 0; counter--)
{
((MyDelegate)delegateList [计数器])();
}
}


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! */ }
}

解决方案

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

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

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