void Main() { string value = @"C:\"; if (!string.IsNullOrEmpty(value)) { string sDirectory = Path.GetDirectoryName(value); } }
它编译.
如果我写的话
void Main() { string value = @"C:\"; if (!string.IsNullOrEmpty(value)) string sDirectory = Path.GetDirectoryName(value); }
不是吗
很明显,从纯功能的角度来看,第二个例子中变量的声明是无用的,但是为什么在第一个例子中魔术变得有用,所以呢?
两个例子产生的IL代码完全一样.
IL_0000: ldstr "C:\" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call System.String.IsNullOrEmpty IL_000C: brtrue.s IL_0015 IL_000E: ldloc.0 IL_000F: call System.IO.Path.GetDirectoryName
编辑:
解决方法
if-statement: if ( boolean-expression ) embedded-statement if ( boolean-expression ) embedded-statement else embedded-statement
C#规范第8部分的开头在给出规范之后,明确地谈到嵌入式语句生成:
06001
The embedded-statement nonterminal is used for statements that appear within other statements. The use of embedded-statement rather than statement excludes the use of declaration statements and labeled statements in these contexts. The example
06002
results in a compile-time error because an if statement requires an embedded-statement rather than a statement for its if branch. If this code were permitted,then the variable i would be declared,but it could never be used. Note,however,that by placing i’s declaration in a block,the example is valid.
请注意,分配计算为表达式语句 – 但是局部变量声明不是. (这是一个声明声明,如第8.5节所述)
在设计决策方面,声明一个你不能使用的变量是没有意义的 – 所以编译器阻止你这样做.