加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:23:34 所属栏目:百科 来源:网络整理
导读:为什么我写 void Main(){ string value = @"C:"; if (!string.IsNullOrEmpty(value)) { string sDirectory = Path.GetDirectoryName(value); }} 它编译. 如果我写的话 void Main(){ string value = @"C:"; if (!string.IsNullOrEmpty(value)) string sDire
为什么我写
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节所述)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读