1

Web サービスがあり、コンストラクターで多くのメソッドを開始します。これらの「終了」(データベース接続の終了など)の多くが必要です。コンストラクター(デコンストラクター)に少し似た、これを行う簡単でダンディな方法はありますか?メソッドは webservice メソッド呼び出しの最後に実行されましたか? 各メソッドの最後にすべてを繰り返すのは、もっとスマートな方法があるに違いないと感じます。

私が選んだ言語は c# です

4

2 に答える 2

3

このアプローチはどうですか?

    private void WebMethodAction()
    {
        Execute(() =>
        {
            Console.WriteLine("Hello World");
        });
    }

    private int WebMethodFunc(int a, int b)
    {
        return Execute(() =>
        {
            return (double)a / (double)b;
        });
    }        

    public void Execute(Action action)
    {
        // call Execute<T> and discard result
        Execute(() => { action.Invoke(); return true; });
    }

    public T Execute<T>(Func<T> func)
    {
        T result = func.Invoke();

        // cleanup
        Console.WriteLine("Cleanup");

        return result;
    }
于 2012-06-07T08:43:22.103 に答える
0

try finallyを使用して、すべての整理を finally セクションに配置できます。

これを Web サービス メソッド内に配置します。

[WebMethod]
public void DoSomething(string value)
{
    try
    {
       //Do Something
    }
    finally
    {
       //Tidy up after methods in the try have ended
    }
}
于 2012-06-07T08:40:45.497 に答える