【问题标题】:Why is a private variable defined in for conflict with the same variable outside? [duplicate]为什么定义的私有变量与外部相同的变量冲突? [复制]
【发布时间】:2014-03-02 12:27:49
【问题描述】:

在我的心智模型中,for 内部定义的计数器变量变为私有,因为它无法从外部访问,如下所示。

    for (int x = 0; x < 2; x++) ;
    //Console.WriteLine(x); x does not exist in the current context

当我如下声明相同的变量时,我的困惑发生了,

    for (int x = 0; x < 2; x++) ;
    //Console.WriteLine(x); x does not exist in the current context, but why cannot I declare
    //int x = 1;

为什么编译器不允许我声明一个与另一个不可访问变量同名的变量?这对我来说没有意义。 :-)

比较一下比较容易混淆

    {
        int x = 1;
    }
    {
        int x = 2;
    }

这是编译器允许的。但以下两种都是不允许的。

static void Foo()
{
    int x = 1;
    { int x = 2; }
}

static void Bar()
{
    { int x = 2; }
    int x = 3;
}

【问题讨论】:

标签: c#


【解决方案1】:

language spec 的第 3.7 节介绍了此行为。它说,“在local-variable-declaration (8.5.1) 中声明的局部变量的范围是发生声明的块”。

x 的范围因此是整个函数,这意味着在 for 循环中的使用是重复使用,因此是不允许的。

这种行为旨在减少不正确地重复使用变量名(例如在剪切和粘贴中)。

【讨论】:

    【解决方案2】:

    aleroot 已经为您的第一部分提供了answer。我想回答你问题的第二部分。

    {
         int x = 1;
    }
    {
         int x = 2;
    }
    

    这是编译器允许的。

    是的,因为在同一作用域或任何嵌套作用域中都没有局部变量x。例如;

    static void Main()
    {
        int x;
        {
            int y;
            int x; // Error - x already defined in same scope or parrent scope.
        }
        {
            int y; // OK - there is no y in the same scope or any nested scope.
        }
        Console.Write (y); // Error - there is no y in same scope of any parrent scope.
    }
    

    【讨论】:

    • 如果第一个 int x; 移动到最后一行,例如在 Console.WriteLine(y); 之后,编译器仍然不满意。在我的心智模型中,这应该不是问题,因为它排在最后。
    • @TheLastError 这是因为在子作用域中已经定义了一个x。如果已经在子范围内,则不能在当前或父范围内声明 local-variable-declaration(不管是最后还是第一个)。
    • 好的。谢谢。一目了然,这是反直觉的。 :-)
    【解决方案3】:

    因为for循环几乎在其中声明了x变量,所以你不能重新声明x变量,因为在范围内只能存在一个声明。

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 2013-11-13
      • 2011-08-24
      相关资源
      最近更新 更多