2014-03-28 35 views
2

我有一個非常簡單的問題。我有代表Lambda表達式C#瞭解甚少。我有代碼:從代表調用列表中獲取結果

class Program 
{ 
    delegate int del(int i); 
    static void Main(string[] args) 
    { 
     del myDelegate = Multiply; 
     int j; 

     myDelegate = x => { Console.WriteLine("Lambda Expression Called..."); return x * x; };    
     myDelegate += Multiply; 
     myDelegate += Increment; 

     j = myDelegate(6); 

     Console.WriteLine(j); 
     Console.ReadKey(); 
    } 

    public static int Multiply(int num) 
    { 
     Console.WriteLine("Multiply Called..."); 
     return num * num; 
    } 
    public static int Increment(int num) 
    { 
     Console.WriteLine("Increment Called..."); 
     return num += 1; 
    } 
} 

,其結果是:

Lambda Expression Called... 
Multiply Called... 
Increment Called... 
7 

它顯示的結果從調用列表中最後調用的方法7

我怎樣才能得到委託調用列表中的每個方法的結果?我看過這thread但我無法理解這個想法。如果您能提供上面提供的我的代碼的答案,我將不勝感激。

謝謝!

回答

1

這是相當不尋常的使用.NET代表的組播能力比事件的用戶以外的任何其他(簡單地考慮使用一個集合,而不是)。

也就是說,可以讓包含多播委託的單個委託(使用Delegate.GetInvocationList)並依次調用它們中的每一個,而不是讓框架爲您執行(通過直接調用多播委託)。這樣,可以檢查調用列表中每個成員的返回值。

foreach(del unicastDelegate in myDelegate.GetInvocationList()) 
{ 
    int j = unicastDelegate(6); 
    Console.WriteLine(j); 
} 

輸出:

Lambda Expression Called... 
36 
Multiply Called... 
36 
Increment Called... 
7 
+0

所以,我可以得到結果時調用已經完成。有沒有辦法在調用時獲得結果?像someVariable = myDelegate + =增量; ? –