【发布时间】:2017-12-13 17:42:52
【问题描述】:
using System.Net; // (See Chapter 16)
...
string s = null;
using (WebClient wc = new WebClient()) // why there is no brackets after this using statement
try { s = wc.DownloadString ("http://www.albahari.com/nutshell/"); }
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.Timeout)
Console.WriteLine ("Timeout");
else
throw; // Can't handle other sorts of WebException, so rethrow
}
上面的代码是从第 153 页 c# in a Nutshell 复制的,我不明白为什么在 using 语句之后缺少 { },这是书中的错字(不太可能)还是不需要?由于语法是使用需要在 {} 中跟随一段代码。
我希望这段代码是:
using System.Net; // (See Chapter 16)
...
string s = null;
using (WebClient wc = new WebClient()) // why there is no brackets after this using statement
{
try { s = wc.DownloadString ("http://www.albahari.com/nutshell/"); }
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.Timeout)
Console.WriteLine ("Timeout");
else
throw; // Can't handle other sorts of WebException, so rethrow
}
}
【问题讨论】:
-
我们使用块
{ }来引入多行范围,当我们想要引入单行范围时我们不使用它们if(true) return;在这种情况下 @987654325 @ 语句将引入它自己的多行范围。所以这不是必需的。 -
只有当你想要包含多个语句时才需要花括号。 try-catch 是一个语句,因此不需要它们,但这是一种不好的形式。从技术上讲,您可以删除所有花括号,代码仍然会以相同的方式运行。
-
我也觉得不妥
-
@Mahmoud 谢谢,但是如果我加上括号,没有副作用吧?谢谢
-
@juharr 你的意思是在 using 语句之后保留括号而不是删除它更好,对吧?谢谢。