【问题标题】:How does scope factor into "do...while" loops and vice versa? [duplicate]范围如何影响“do...while”循环,反之亦然? [复制]
【发布时间】:2013-03-24 12:14:16
【问题描述】:

C# 作业问题:我刚刚使用 do-while 循环添加了一些“再次播放”逻辑。这是我的原始代码:

namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Info myInfo = new Info();
            myInfo.DisplayInfo("Daniel Wilson", "4 - Hi-Lo Game");
               // I moved  String playAgain = "N"; to here 
            do
            {
                DWHiLowUI theUI = new DWHiLowUI();
                theUI.Play();
                String playAgain = "N";
                Console.WriteLine("Enter 'Y' to play again, any other key to exit.");
                playAgain = Console.ReadLine();
            }
            while ((playAgain == "Y")||(playAgain =="y"));
            Console.ReadLine();
        }
    }
}

这给了我一个错误:

Error   7   The name 'playAgain' does not exist in the current context

我将String playAgain = "N"; 移动到我的do 上方的行(见评论),它运行良好。

我试图了解我究竟做了什么 来解决这个问题。这似乎是一个范围问题,但在我看来,在循环中定义一个变量可以想象将它传递到循环的末尾。我浏览了我的教科书,没有任何关于范围的内容,因为它与循环有关。这向我表明循环内的范围不是问题,但这表现得好像它是一个范围问题。想了想我自己都糊涂了。

如果它是一个范围问题,我想更好地了解方法中do...while 循环的范围。如果它不是范围问题,那是我的幸运猜测。在那种情况下出了什么问题,移动那行代码是如何解决的?

【问题讨论】:

    标签: c# loops scope


    【解决方案1】:

    你是对的,这是一个范围界定问题。 C# 具有 块作用域,这意味着在块内声明的变量(在 {} 之间声明的代码)只能在该块(和子块)内访问。

    由于playAgain 是在循环体内部定义的,因此在该块之外无法访问它,即使在while 表达式中也是如此。

    【讨论】:

      【解决方案2】:

      是的,这是范围问题。 do..while 周围的范围如下所示

      // outer scope
      do 
      {
          // inner scope
      } while (/*outer scope*/);
      // outer scope
      

      【讨论】:

        【解决方案3】:

        添加..循环的每次迭代都会破坏该块中定义的变量,因此当您处于块外的条件评估中时不知道内部上下文中定义的playAgain是什么。

        【讨论】:

          猜你喜欢
          • 2011-12-25
          • 2016-01-24
          • 1970-01-01
          • 2011-04-07
          • 1970-01-01
          • 2021-12-12
          • 1970-01-01
          • 2021-11-20
          • 1970-01-01
          相关资源
          最近更新 更多