【问题标题】:C# local variable scope [duplicate]C#局部变量范围[重复]
【发布时间】:2012-08-22 02:49:11
【问题描述】:

可能重复:
confused with the scope in c#

似乎在 C# 中,使用 if/else/loop 块的局部范围定义的变量与在该块之后定义的变量冲突 - 请参阅代码片段。等效代码在 C/C++ 和 Java 下编译得很好。这是 C# 中的预期行为吗?

public void f(){
  if (true) {
    /* local if scope */
    int a = 1;
    System.Console.WriteLine(a);
  } else {
    /* does not conflict with local from the same if/else */
    int a = 2;
    System.Console.WriteLine(a);
  }

  if (true) {
    /* does not conflict with local from the different if */
    int a = 3;
    System.Console.WriteLine(a);
  }

  /* doing this:
   * int a = 5;
   * results in: Error 1 A local variable named 'a' cannot be declared in this scope
   *  because it would give a different meaning to 'a', which is already used in a 
   *  'child' scope to denote something else
   * Which suggests (IMHO incorrectly) that variable 'a' is visible in this scope
   */

  /* doing this: 
   * System.Console.WriteLine(a);
   * results in: Error 1 The name 'a' does not exist in the current context..
   * Which correctly indicates that variable 'a' is not visible in this scope
   */
}

【问题讨论】:

标签: c#


【解决方案1】:

是的,这就是 C# 的工作原理。

当声明一个作用域时,任何来自外部作用域的局部变量也是已知的——没有办法限定作用域内的局部变量应该覆盖外部的局部变量。

【讨论】:

  • 看来它归结为“范围内”定义。在 C# 中与 (C++) 不同,如果在块内定义局部变量 - 无论声明的位置如何,它都在整个块内的范围内。而在 C++ 中,在块内定义的局部变量仅在声明之后的点在范围内
【解决方案2】:

您似乎关心声明的顺序(在if 块之后重新声明a )。

考虑在if 块之前声明它的情况。那么你会期望它在这些块的范围内可用。

int a = 1;

if(true)
{
  var b = a + 1; // accessing a from outer scope
  int a = 2; // conflicts
}

在编译时实际上并没有“不在范围内”的概念。

您实际上可以只用大括号创建一个内部作用域:

{
   int a = 1;
}

if(true)
{
   int a = 2; // works because the a above is not accessible in this scope
}

【讨论】:

    【解决方案3】:

    这是正常行为。

    Sam Ng 不久前写了一篇很好的博文:http://blogs.msdn.com/b/samng/archive/2007/11/09/local-variable-scoping-in-c.aspx

    【讨论】:

      【解决方案4】:

      已经有一些很好的答案,但我查看了 C# 4 语言规范以澄清这一点。

      我们可以在 §1.24 中阅读关于范围的内容:

      作用域可以嵌套,内部作用域可以重新声明 来自外部范围的名称(但是,这不会删除 §1.20 施加的限制,即在嵌套块中它不是 可以声明一个与局部变量同名的局部变量 封闭块中的变量)。

      这是第 1.20 节中引用的部分:

      声明在声明空间中定义了一个名称, 声明属于。除了重载成员(§1.23),它是一个 有两个或多个声明引入的编译时错误 声明空间中具有相同名称的成员。它从来不是 声明空间可能包含不同类型的成员 同名

      [...]

      请注意,作为函数成员体或在函数体中出现的块 或匿名函数嵌套在局部变量声明中 这些函数为其参数声明的空间。

      【讨论】:

        【解决方案5】:

        是的。这是预期的,因为您在 local 语句中定义变量。如果您要在类级别定义变量,您会得到不同的结果。

        【讨论】:

          猜你喜欢
          • 2014-10-25
          • 2012-11-05
          • 2014-05-02
          • 2010-09-13
          • 2014-03-02
          • 2012-08-21
          • 2015-09-26
          • 2013-10-14
          • 2013-02-15
          相关资源
          最近更新 更多