我怎样才能避免重复的try catch块 [英] How can I avoid duplicated try catch blocks
问题描述
我有几种方法是这样的:
I have several methods that look like this:
public void foo()
{
try
{
doSomething();
}
catch(Exception e)
{
Log.Error(e);
}
}
我可以更改code到什么样子的?
Can I change the code to look like?
[LogException()]
public void foo()
{
doSomething();
}
我怎样才能实现这个自定义属性?什么是这样做的利弊?
How can I implement this custom attribute? and what are the pros and cons of doing it?
-----编辑1 ------------
-----Edit 1------------
我能实现我自己,我的意思是只写一个类,或者我需要使用postsharp或其他解决方案?
Can I implemented it myself, I mean just write one class, or do I need to use postsharp or another solution?
推荐答案
您可以使用委托和lambda表达式:
You can use delegates and 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);
});
}
在事实上,你可以重命名 ExecuteWithLogging
来像 ExecuteWebserviceMethod
并添加其他常用的东西,如检查凭据,打开和关闭数据库连接等。
In fact, you could rename ExecuteWithLogging
to something like ExecuteWebserviceMethod
and add other commonly used stuff, such as checking credentials, opening and closing a database connection, etc.
这篇关于我怎样才能避免重复的try catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!