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 }
上面的代码是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 } }
解决方法
如果你看一下
C# Specification中using语句的语法,你会看到using语句后跟(或者更确切地说,它们的主体由“embedded_statements”组成).
using_statement : 'using' '(' resource_acquisition ')' embedded_statement ;
嵌入式语句定义如下:
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 ;
所以是的,这不是一个错字.使用(…)之后,可以在embedded_statement中定义任何语句.无论如何,要想看这是否是一个错字,你可能只是简单地尝试编译示例代码.