微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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节所述)

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

原文地址:https://www.jb51.cc/csharp/95742.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐