デリゲートを使ったテンプレート
ある処理の最初と最後は共通なんだけど。とかいったときに。
/// <summary> /// テンプレート実行。 /// </summary> /// <param name="func">実行対象デリゲート。</param> /// <param name="args">デリゲートに渡す引数。</param> /// <returns>実行結果。</returns> public static object Execute( Delegate func, params object[] args ) { try { return func.DynamicInvoke( args ); } catch (Exception ex) { MessageBox.Show( ex.ToString() ); throw; } }
使い方。
public static void DoTest() { Execute( new Action( VoidDo ) ); Execute( new Action<string, string, string>( VoidDo ), "a", "b","c" ); Execute( new Func<int>( RetDo ) ); Execute( new Func<string, string, string, int>( RetDo ), "d", "e", "f" ); } static void VoidDo() { Console.WriteLine( "VoidDo" ); } static void VoidDo( string arg1, string arg2, string arg3 ) { Console.WriteLine( "VoidDo" + arg1 + arg2 + arg3 ); } static int RetDo() { Console.WriteLine( "RetDo" ); return 1; } static int RetDo( string arg1, string arg2, string arg3 ) { Console.WriteLine( "RetDo" + arg1 + arg2 + arg3 ); return 4; }
Action とか Func とか便利な世の中になったもんだ。