所以我在方法中有以下代码块:(所有变量都是本地的)
// ...
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语句是完全一样的。我一直在想一种方法,可以不在这里重复自己,但我还没有真正想到一种方法不会显着变慢或看起来很糟糕。想知道是否有人有任何想法。