2012-05-07 15 views
0

ソースコードをDRYしたいです。主に1行で異なるこれらの機能がいくつかあったとします。これをどのように達成できますか?さまざまなパラメータを持つデリゲートを使用する

public Result foo (int x, int y, int z){ 
    Log.Say("Foo started!");         <<< DIFFERENCE 
    DoSomeMagic(); 
    try { 
     result = controller.foo(x, y, z);     <<< DIFFERENCE 
    } catch (Exception){ 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 


public Result bar (Person a, string whatever){ 
    Log.Say("Bar started!");         <<< DIFFERENCE 
    DoSomeMagic(); 
    try { 
     result = controller.bar(a, whatever);    <<< DIFFERENCE 
    } catch (Exception) { 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 

これは難しいことではありません。私は今もさまざまなアプローチによって混乱しています。これまで私は代理人、 Func、ラムダ式、匿名関数とそれをやろうとしましたが、私はそれを動作させることができません(私は休憩が必要です)。さらにとして

public Result handler (Func callbackMethodWithArgs) { 
    Result result = null; 
    Log.Say(method + " started!"); 
    DoSomeMagic(); 
    try { 
     result = invoke(callbackMethodWithArgs) as Result; 
    } catch (Exception) { 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 

public Result foo (int x, int y, int z) { 
    return handler(controller.foo(x, y, z)); 
} 

public Result bar (Person a, string whatever) { 
    return handler(controller.bar(a, whatever); 
} 

public Result foo (int x, int y, int z) { 
    return handler(delegate() { 
     controller.foo(x, y, z)); 
     doSomethingOther(); 
    }); 
} 

任意の提案のように、無名関数を使用する可能性を持っていることは本当に素晴らしいことです?ありがとう! (私は似たような話題について多くの質問を読んだが、問題を解決したものは何も見つかりませんでした - そうなら、おそらく重複していると思います)

答えて

2

Func<Result>:呼び出しサイトで

public Result handler (string name, Func<Result> method) { 
    Result result = null; 
    Log.Say(name + " started!"); 
    DoSomeMagic(); 
    try { 
     result = method(); 
    } catch (Exception) { 
     Log.Say("Something went terribly wrong"); 
    } 
    return result; 
} 

そして代表者にそれらを回す:

public Result foo (int x, int y, int z) { 
    return handler("Foo",() => controller.foo(x, y, z)); 
} 

public Result bar (Person a, string whatever) { 
    return handler("Bar",() => controller.bar(a, whatever); 
} 

注:.NET 2.0にしている場合は、上記のコードを使用する前に、手動でFunc<_>デリゲートを作成することができます。

public delegate TResult Func<TResult>(); 

例外として、このように例外を隠すことは良い考えではありません。あなたはnullを返すだけで、例外をログに記録し直すのではなく、呼び出しコードが何をすべきかを決めることができます。あなたのユースケースでは動作しますが、一般的には赤い旗です。

+0

私はあなたの方法を好き:) – ykatchou

+0

あなたはどの.NETバージョンですか? – yamen

+0

.NET 4を使用しています –

関連する問題