c# – 为什么这个编译错误

为什么我写
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

编辑:

忘记了为第二种情况生成IL代码(所以不可编译的情况),只要编译没有字符串sDirectory =

解决方法

if语句的生成在C#规范的第8.7.1节中,它如下所示:
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节所述)

在设计决策方面,声明一个你不能使用的变量是没有意义的 – 所以编译器阻止你这样做.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...