2014-04-04 74 views
1

我有很簡單的委託Invoke方法的所有結果:如何獲得

public delegate int Compute(int i, int j); 

和一些功能:

static int sum(int x, int y) 
{ 
    return x + y; 
} 

static int diff(int x, int y) 
{ 
    return x - y; 
} 

static int times(int x, int y) 
{ 
    return x * y; 
} 

然後我聲明的事件爲:

public static event Compute e; 

在主要我正在爲事件添加功能:

e += new Compute(sum); 
    e += new Compute(diff); 
    e += new Compute(times); 

最後,我想編寫的函數的所有結果,所以:

Console.WriteLine(e.Invoke(3,4)); 

我的理解Invoke方法調用在事件中的所有功能。但在我的情況下,我只看到最後一個附加功能的結果 - 所以12。我如何獲得Invoke方法的所有結果?

如果函數沒有返回任何類型(它們是void類型)沒有問題,但是如果函數返回一些東西 - 那就是。

+2

這似乎有點[xy問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)你真的想用這個解決什麼問題? – asawyer

回答

5

你必須調用MulticastDelegate.GetInvocationList,這將讓你在同一時間調用一個處理程序:

// TODO: Don't call your event e, and use Func<int, int, int> 
foreach (Compute compute in e.GetInvocationList()) 
{ 
    int result = compute(3, 4); 
    Console.WriteLine("{0} returned {1}", compute.Method.Name, result); 
} 
0

它是由設計。如果你想獲得所有結果,你必須使用GetInvokationList()方法得到委託列表,然後按列表迭代並調用所有委託。