2010-06-09 45 views
12

當您在.NET中訂閱事件時,訂閱將添加到多播委託中。當事件被觸發時,代表按照他們訂閱的順序被調用。我可以顛倒多播委託事件的順序嗎?

我想以某種方式覆蓋訂閱,以便訂購實際上在反向訂單中被解僱。可以這樣做,以及如何?

我覺得這樣的事情可能是我需要什麼?:

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

我認爲訂閱被解僱的訂單是不確定的。 – ChrisF 2010-06-09 22:07:00

+0

@ChrisF:From MSDN ...「MulticastDelegate有一個委託鏈表,稱爲調用列表,由一個或多個元素組成,當調用多播委託時,調用列表中的委託按順序同步調用他們出現在這裏。「 – 2010-06-09 22:08:02

+0

@羅伯特 - 啊,我明確地掩飾了**多播**位 - 時間停止尋找問題來回答和睡覺。 – ChrisF 2010-06-09 22:10:40

回答

5

Controlling When and If a Delegate Fires Within a Multicast Delegate

下面的方法創建一個名爲allInstances多播委託,然後使用GetInvocationList,讓每位代表進行單獨發射,以相反的順序:

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

謝謝 - 我在你發佈你的答案之前自己試過了,並且得到了它的工作 - 很高興看到我確實做了正確的事情。 :) – 2010-06-09 22:15:48

5

一個辦法是,當你擡起事件來處理這個問題。您可以通過Delegate.GetInvocationList獲得活動訂閱者,並且只需按照相反順序調用每個代理。

+0

謝謝 - 我只是在你發佈你的答案之前自己試過了這個,並且得到了它的工作 - 很高興看到我確實做了正確的事情。 :) – 2010-06-09 22:16:28

+0

@SLaks:有趣。謝謝 - 以前沒有用過這種方式的代表操作員...... – 2010-06-10 00:40:52

19

你不需要任何魔法;你只需要扭轉添加。
書寫delegate1 + delegate2返回一個新委託,其中包含delegate1中的方法,然後是delegate2中的方法。

例如:

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

你並不需要在remove處理任何魔法,除非你想刪除處理不是第一個的最後出現。 (如果相同的處理程序被添加兩次)

+0

你能擴展一下你的答案嗎?很高興看到你發佈的代碼的上下文,所以我可以看到我應該把它放在哪裏。 – 2010-06-09 22:17:11

+0

感謝您的答案更新。 – 2010-06-09 22:19:08

+0

@Neil,這裏有一些背景資料:http://www.gavaghan.org/blog/2007/07/25/intercepting-add-and-remove-of-c-event-delegates/ – 2010-06-09 22:19:44