我有一个类,其中包含大约 20 多个方法。每个都进行一些 Web 服务消息处理。我只需要对其进行更改,并意识到这些方法中的每一个都有完全相同的 try/catch:
try
{
/* *** actual processing specific to each method goes here *** */
}
catch (FaultException<CustomException> cfex)
{
// common stuff
}
catch (CustomException cfex)
{
// common stuff
}
catch (Exception ex)
{
// common stuff
}
finally
{
FinalizeServiceCall(wsBus, wsMessage, response, logProps);
}
我的问题是;不是在每个方法中都使用完全相同的 try/catch block ,有没有办法让它变得通用?我的想法是 .NET 有类似 TransactionScope
的东西,它以某种方式检测离开该 block 时是否发生异常。我是否可以利用类似的东西来制作一个通用的 try/catch block ?还有其他想法吗?
最佳答案
我会这样做:
创建一个包含 try/catch 的方法并将 Action
传递给它并在 try 部分执行该操作:
public void Method1()
{
Action action = () =>
{
// actual processing of Method 1
};
SafeExecutor(action);
}
public void Method1b()
{
SafeExecutor(() =>
{
// actual processing of Method 1
});
}
public void Method2(int someParameter)
{
Action action = () =>
{
// actual processing of Method 2 with supplied parameter
if(someParameter == 1)
...
};
SafeExecutor(action);
}
public int Method3(int someParameter)
{
Func<int> action = () =>
{
// actual processing of Method 3 with supplied parameter
if(someParameter == 1)
return 10;
return 0;
};
return SafeExecutor(action);
}
private void SafeExecutor(Action action)
{
SafeExecutor(() => { action(); return 0; });
}
private T SafeExecutor<T>(Func<T> action)
{
try
{
return action();
}
catch (FaultException<CustomException> cfex)
{
// common stuff
}
catch (CustomException cfex)
{
// common stuff
}
catch (Exception ex)
{
// common stuff
}
finally
{
FinalizeServiceCall(wsBus, wsMessage, response, logProps);
}
return default(T);
}
SafeExecutor
的两个版本让您可以处理有和没有返回类型的方法。
Method1b
显示您的方法中不需要变量 action
,如果您认为这样更易读,可以将其内联。
关于c# - 关于在 C# 中制作可重用的 try/catch block 的建议?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6046382/