C#Homework问题:我刚刚使用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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个错误:
Error 7 The name 'playAgain' does not exist in the current context
Run Code Online (Sandbox Code Playgroud)
我移动String playAgain = "N";
到了我的上面一行do
(见评论),它工作正常.
我想知道我到底做了什么来解决这个问题.这似乎是一个范围问题,但在我看来,在循环中定义一个变量可以想象地将它传递给循环的末尾.我查看了我的教科书,并没有关于范围的任何内容,因为它与循环有关.这会告诉我,循环中的范围不是问题,但这表现得好像是范围问题.我很困惑自己在思考它.
如果这是一个范围问题,我想更好地理解do...while
方法中的循环范围.如果它不是范围问题,那对我来说是一个幸运的猜测.在那种情况下出了什么问题以及如何移动这行代码来修复它?
你是对的,这是一个范围问题.C#具有块作用域,这意味着在块内声明的变量(在其间声明的代码{}
)只能在该块(和子块)内部访问.
由于playAgain
在循环体内部定义,因此在该块之外不可访问,甚至在while
表达式内也不可访问.
是的,这是范围问题.围绕do..while的工作范围如下
// outer scope
do
{
// inner scope
} while (/*outer scope*/);
// outer scope
Run Code Online (Sandbox Code Playgroud)