c#“using”语句后跟try语句可以在这种情况下对括号进行ombitted
发布时间:2020-12-15 04:17:22 所属栏目:百科 来源:网络整理
导读: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 (WebExcepti
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中定义任何语句.无论如何,要想看这是否是一个错字,你可能只是简单地尝试编译示例代码. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |