ソースコードを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();
});
}
任意の提案のように、無名関数を使用する可能性を持っていることは本当に素晴らしいことです?ありがとう! (私は似たような話題について多くの質問を読んだが、問題を解決したものは何も見つかりませんでした - そうなら、おそらく重複していると思います)
私はあなたの方法を好き:) – ykatchou
あなたはどの.NETバージョンですか? – yamen
.NET 4を使用しています –