如何避免重复的try catch块

Del*_*ate 11 c# attributes try-catch

我有几个方法看起来像这样:

public void foo()
{
   try 
   {
      doSomething();
   }
   catch(Exception e)
   {
      Log.Error(e);
   }
 }
Run Code Online (Sandbox Code Playgroud)

我可以更改代码吗?

[LogException()]
public void foo()
{   
   doSomething();
}
Run Code Online (Sandbox Code Playgroud)

如何实现此自定义属性?这样做的利弊是什么?

-----编辑1 ------------

我可以自己实现它,我的意思是只写一个类,还是我需要使用postharp或其他解决方案?

Hei*_*nzi 12

您可以使用委托和lambdas:

private void ExecuteWithLogging(Action action) {
    try {
        action();
    } catch (Exception e) {
        Log.Error(e);
    }
}

public void fooSimple() {
    ExecuteWithLogging(doSomething);
}

public void fooParameter(int myParameter) {
    ExecuteWithLogging(() => doSomethingElse(myParameter));
}

public void fooComplex(int myParameter) {
    ExecuteWithLogging(() => {
        doSomething();
        doSomethingElse(myParameter);
    });
}
Run Code Online (Sandbox Code Playgroud)

实际上,您可以重命名ExecuteWithLogging为类似的东西ExecuteWebserviceMethod并添加其他常用的东西,例如检查凭据,打开和关闭数据库连接等.