0

ソースコードを乾かしたい。主に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、Lambda式、無名関数を使用してそれを実行しようとしましたが、機能させることができません(休憩が必要だと思います)。

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();
    });
}

助言がありますか??ありがとう!(私は同様のトピックに関する多くの質問を読みましたが、私にとって問題を解決するものは何も見つかりませんでした-それでおそらく重複していると思います-もしそうなら、ごめんなさい)

4

1 に答える 1

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 を返して例外をログに記録するだけです。あなたのユースケースではうまくいくかもしれませんが、一般的には危険信号です。

于 2012-05-07T12:12:37.487 に答える