首先,听起来您可能过于频繁地使用 try/catch - 特别是如果您正在使用Exception
. try/catch 块应该是比较少见的;除非您真的可以“处理”异常,否则您应该让它冒泡到堆栈的下一层。
现在,假设您确实想要所有这些 try/catch 块,为什么不能选择创建委托?使用匿名方法和 lambda 表达式,以及System
命名空间中的 Func/Action 委托,基本上几乎没有什么工作要做。你写:
public void SurroundWithTryCatch(Action action)
{
try
{
action();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
然后你SurroundWithTryCatch(MyMethod)
会正常工作,如果它不需要参数的话。
或者,如果您不想调用其他方法,只需编写:
public void MyMethod()
{
SurroundWithTryCatch(() =>
{
// Logic here
});
}
如果您需要从该方法返回,您可以执行以下操作:
public int MyMethod()
{
return SurroundWithTryCatch(() =>
{
// Logic here
return 5;
});
}
SurroundWithTryCatch
像这样的通用重载:
public T SurroundWithTryCatch<T>(Func<T> func)
{
try
{
return func();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
其中大部分在 C# 2 中也可以,但类型推断对您的帮助不大,您必须使用匿名方法而不是 lambda 表达式。
回到开始:尽量少用 try/catch。(try/finally 应该更频繁,尽管通常写成 using 语句。)