我有几种类似这样的方法:
public void foo()
{
try
{
doSomething();
}
catch(Exception e)
{
Log.Error(e);
}
}
我可以把代码改成这样吗?
[LogException()]
public void foo()
{
doSomething();
}
如何实现这个自定义属性?这样做的优点和缺点是什么?
-----编辑1------------
我可以自己实现它,我的意思是只写一个类,还是我需要使用 postsharp 或其他解决方案?
您可以使用委托和 lambda:
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
并添加其他常用的内容,例如检查凭据、打开和关闭数据库连接等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)