【问题标题】:How are the do-while loops compiled?do-while 循环是如何编译的?
【发布时间】:2018-07-10 04:13:12
【问题描述】:

这些问题实际上比标题更具体。 我只是在浏览一些 C#,遇到了一个我设法修复的错误,但我不知道为什么。

为什么在循环中定义了字符串幂时,我的 do-while 循环给了我一个错误?

不过,当我在 do-whiel 循环之前定义我的弦乐功率时,一切都很好,很花哨

        String power;

        do
        {
            Console.WriteLine("Enter values X & Y for X+Y");

            Console.WriteLine("Your value of X is  ");
            int numOne = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(" Your value of Y is   ");
            int numTwo = Convert.ToInt32(Console.ReadLine());


            Console.WriteLine("Your Sum is {0}", numOne+numTwo);


            Console.Write("Turn calculator on or off?    ");
            power = Console.ReadLine();

        } while (power == "on" || power =="On" || power =="ON");
    }
}

}

这最终运行良好。

但是下面的例子在 while 语句中导致了关于名称“power”在当前上下文中不存在的错误。

     do
        {
            Console.WriteLine("Enter values X & Y for X+Y");

            Console.WriteLine("Your value of X is  ");
            int numOne = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(" Your value of Y is   ");
            int numTwo = Convert.ToInt32(Console.ReadLine());


            Console.WriteLine("Your Sum is {0}", numOne+numTwo);


            Console.Write("Turn calculator on or off?    ");
            String power;

            power = Console.ReadLine();

        } while (power == "on" || power =="On" || power =="ON");
    }
}

【问题讨论】:

  • 将花括号 { 和 } 视为局部变量的范围。在第二种情况下的 while 条件中,power 是 while 语句作用域的主体。
  • while 本身超出了do 的范围。那就是它无法访问do 中定义的电源。
  • oN 怎么样?或者,您可以使用power = Console.ReadLine().ToLower()while (power == "on")

标签: c# string loops variables do-while


【解决方案1】:

{ .......... } 创建一个范围。在循环内部定义比while (power...) 部分更深的范围。

基本上,您可以看到嵌套较少的作用域(if 的作用域可以看到方法作用域,方法作用域可以看到类作用域,类可以看到命名空间作用域等。

有关范围界定的更多信息,请参阅here

另一个例子:

public void A()
{
    string power = "test";

    {
         // this works because power is defined in a less deep scope.
         Console.WriteLine(power);
    }
}

public void B()
{
    {
        string power = "test";
    }
    // this doesn't work because power is defined in a deeper scope
    Console.WriteLine(power); 
}

错误消息所指的“上下文”是:当前范围及其之上的所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2021-07-27
    相关资源
    最近更新 更多