マルチキャストデリゲートのそれぞれの戻り値を得る方法
チェーンになったデリゲートを普通に実行すると、最後の戻り値しか取れません。でも、もちろん、それぞれの戻り値を得ることもできます。C#を学び始めたばかりのころ、このやり方がわからなくて悔しかった。なのでメモしとく。リッチャー本で知った技。
サンプルなのでエラーチェックは雑です。
using System; using System.Collections.Generic; //public delegate int Calc( int l, int r ); class Program { delegate int Calc( int l, int r ); static void Main() { Calc chain = null; chain += delegate( int l, int r ) { return l + r; }; chain += delegate( int l, int r ) { return l - r; }; chain += delegate( int l, int r ) { return l * r; }; Console.WriteLine( chain( 10, 5 ) ); Console.WriteLine( "GetAnyResults:" ); GetAnyResults( chain, 10, 5 ).ForEach( Console.WriteLine ); Console.ReadKey(); } static List<int> GetAnyResults( Calc calcChain, int l, int r ) { if ( calcChain == null ) return null; List<int> results = new List<int>(); Delegate[] delegateArray = calcChain.GetInvocationList(); foreach ( Calc calc in delegateArray ) results.Add( calc( l, r ) ); return results; } }
デリゲートはクラスに展開されるので、4行目のような位置にも書けたりします。
(4/11追記)
もっと簡単に書けた。
int[] results = Array.ConvertAll<Delegate, int>( chain.GetInvocationList(), delegate( Delegate d ) { return ( ( Calc ) d )( 10, 5 ); } ); Array.ForEach( results, Console.WriteLine );