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

前端之家收集整理的这篇文章主要介绍了c# – 为什么这个编译错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么我写
  1. void Main()
  2. {
  3. string value = @"C:\";
  4. if (!string.IsNullOrEmpty(value)) {
  5. string sDirectory = Path.GetDirectoryName(value);
  6. }
  7.  
  8. }

它编译.

如果我写的话

  1. void Main()
  2. {
  3. string value = @"C:\";
  4. if (!string.IsNullOrEmpty(value))
  5. string sDirectory = Path.GetDirectoryName(value);
  6.  
  7.  
  8. }

不是吗

很明显,从纯功能的角度来看,第二个例子中变量的声明是无用的,但是为什么在第一个例子中魔术变得有用,所以呢?

两个例子产生的IL代码完全一样.

  1. IL_0000: ldstr "C:\"
  2. IL_0005: stloc.0
  3. IL_0006: ldloc.0
  4. IL_0007: call System.String.IsNullOrEmpty
  5. IL_000C: brtrue.s IL_0015
  6. IL_000E: ldloc.0
  7. IL_000F: call System.IO.Path.GetDirectoryName

编辑:

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

解决方法

if语句的生成在C#规范的第8.7.1节中,它如下所示:
  1. if-statement:
  2. if ( boolean-expression ) embedded-statement
  3. 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节所述)

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

猜你在找的C#相关文章