Hui*_*ang 6 c# using try-catch
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
}
Run Code Online (Sandbox Code Playgroud)
上面的代码是cuts在一个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
}
}
Run Code Online (Sandbox Code Playgroud)
Adr*_*ian 10
如果您查看C#规范中using语句的语法,您会看到using语句后跟(或者更确切地说,它们的主体由"embedded_statements"组成).
using_statement
: 'using' '(' resource_acquisition ')' embedded_statement
;
Run Code Online (Sandbox Code Playgroud)
嵌入式语句定义如下:
embedded_statement
: block
| empty_statement
| expression_statement
| selection_statement
| iteration_statement
| jump_statement
| try_statement
| checked_statement
| unchecked_statement
| lock_statement
| using_statement
| yield_statement
| embedded_statement_unsafe
;
Run Code Online (Sandbox Code Playgroud)
所以是的,这不是一个错字.之后using (...),可以有任何定义的语句embedded_statement.无论如何,要想看这是否是一个错字,你可能只是简单地尝试编译示例代码.
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |