干后用不同try语句和相同的catch语句 [英] DRY With Different Try Statements and Identical Catch Statements

查看:129
本文介绍了干后用不同try语句和相同的catch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个方法中的以下代码块:(所有变量都是局部的)

So I have the following block of code inside a method: (all variables are local)

// ...

try
{
    if (postXml != null)
        using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
            writer.Write(postXml.ToString());
}
catch (WebException ex)
{
    HttpWebResponse response = ex.Response as HttpWebResponse;
    if (response != null)
        result = HandleOtherResponse(response, out status);
    else result = HandleBadResponse(ex.ToString(), out status);
}
catch (Exception ex)
{
    result = HandleBadResponse(ex.ToString(), out status);
}

if (result == null)
{
    try
    {
        HttpWebResponse response = req.GetResponse() as HttpWebResponse;
        result = HandleOtherResponse(response, out status);
    }
    catch (WebException ex)
    {
        HttpWebResponse response = ex.Response as HttpWebResponse;
        if (response != null)
            result = HandleOtherResponse(response, out status);
        else result = HandleBadResponse(ex.ToString(), out status);
    }
    catch (Exception ex)
    {
        result = HandleBadResponse(ex.ToString(), out status);
    }
}

// ...

正如你所看到的,两个try语句是不同的,但两个catch语句是完全相同的。我一直在想方法,这可能是不可能在这里重复自己,但我没有真正想到一个方法,不会显着减慢或只是可怕的看。

As you can see, the two try statements are different, but the two sets of catch statements are exactly the same. I've been trying to think of a way that it might be possible to not repeat myself here, but I haven't really thought of a way that wouldn't be significantly slower or just as terrible looking. Wondering if anyone has any ideas.

推荐答案

一种方法是编写一个安全调用方法,并向其传递一个func :

One way would be to write a "safe" invocation method and pass a func to it:

public T SafeInvocation(Func<T> myMethod)
{
    T result = default(T);

    try
    {
        // Invoke method
        result = myMethod();
    }
    catch
    {
        // Do your common catch here
    }

    return result;
}

为Action< T&所以你不需要有返回类型。然后你可以在别的地方调用它,传递方法到你的方法作为参数(Inception?):

Build an additional overload for Action<T> so that you don't need to have a return type. Then you could invoke it elsewhere, passing methods to your method as arguments (Inception?):

SafeInvocation(() => 
{
    if (postXml != null)
        using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
            writer.Write(postXml.ToString());
}

这篇关于干后用不同try语句和相同的catch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆