2011-12-08 5 views
3

これが可能かどうかはわかりませんが、同じデリゲート(マルチキャスト)に割り当てられた2つのメソッドの戻り値をどのようにキャッチするのか不思議です。私は基本的に各戻り値をキャッチする方法があるのだろうかと思ったのですか?おそらく、私はそれを反復する必要があり、実際にはわからない。..実行時にマルチキャストデリゲートの結果を抽出するにはどうすればよいですか?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace MutiCastDelegate2 
{ 
    class Program 
    { 

     delegate string HelloWorldDelegate(); 

     static void Main(string[] args) 
     { 
      HelloWorldDelegate myDel1 = ReturnHelloWorld; 
      HelloWorldDelegate myDel2 = ReturnHelloWorld2; 
      HelloWorldDelegate myMultiDelegate = myDel1 + myDel2; 

      Console.WriteLine(myMultiDelegate()); 
      Console.ReadLine(); 
     } 


     public static string ReturnHelloWorld() 
     { 
      return "Return Hello World"; 
     } 

     public static string ReturnHelloWorld2() 
     { 
      return "Return Hello World 2"; 
     } 
    } 
} 

答えて

2

あなたは、あなただけのそれぞれを呼び出して結果を取得する必要があり、リスト内の各デリゲートへのアクセスを得るためにMulticastDelegate.GetInvocationList()を使用することができます。

var delegates = myMultiDelegate.GetInvocationList(); 
foreach (var d in delegates) 
{ 
    string result = (string) d.DynamicInvoke(); 
}