如何摆脱尝试捕获?

Raz*_*scu 10 c# error-handling

我对周围的代码感到厌倦,尝试像这样抓住..

try
{
    //some boring stuff
}
catch(Exception ex)
{
    //something even more boring stuff
}
Run Code Online (Sandbox Code Playgroud)

我想要的东西

SurroundWithTryCatch(MyMethod)
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过创建具有该函数的确切签名的委托来完成此行为,但是为我的应用程序中的所有方法创建委托它不是一个选项.

我也可以通过注入IL代码来做到这一点,但这在性能方面很昂贵,因为它在我的周围创建了一个包装器组件.

还有其他有效的想法吗?

Jon*_*eet 24

首先,听起来你可能经常使用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
    }    
}
Run Code Online (Sandbox Code Playgroud)

然后你的SurroundWithTryCatch(MyMethod)意志工作正常,如果不需要参数.

或者,如果您不想调用其他方法,只需写:

public void MyMethod()
{
    SurroundWithTryCatch(() => 
    {
        // Logic here
    });
}
Run Code Online (Sandbox Code Playgroud)

如果您需要从方法返回,您可以执行以下操作:

public int MyMethod()
{
    return SurroundWithTryCatch(() => 
    {
        // Logic here
        return 5;
    });
}
Run Code Online (Sandbox Code Playgroud)

与这样的泛型重载SurroundWithTryCatch:

public T SurroundWithTryCatch<T>(Func<T> func)
{    
    try
    {
        return func();
    }
    catch(Exception ex)
    {
        //something even more boring stuff
    }    
}
Run Code Online (Sandbox Code Playgroud)

大多数情况下也可以在C#2中使用,但是类型推断对你的帮助不大,你必须使用匿名方法而不是lambda表达式.

尽管如此:尽量少尝试使用try/catch.(尝试/最后应该更频繁,尽管通常写为using语句.)