'continue' 的 C# 错误
C# Error with 'continue'
我正在尝试将 if 语句与 bool 一起使用,这将使得如果代码 运行s 一旦它不会再次 运行。这是我正在使用的代码。
int random = Program._random.Next(0, 133);
if (random < 33) {
bool done = false;
if(done)
{
continue; // Error is shown for this statement
}
Console.WriteLine("Not done!");
done = true;
}
Visual Studio 显示的错误是:"No enclosing loop out of which to break or continue"。
根据 class/method 要求,您可能会颠倒逻辑:
if (!done)
{
Console.WriteLine("Not done!");
done = true;
}
不能仅在循环内使用 continue。所以你必须没有这个生活:
int random = Program._random.Next(0, 133);
if(random < 33)
{
bool done = false;
if(!done)
{
Console.WriteLine("Not done!");
done = true;
}
}
在这种情况下,您应该使用 if (!done) { ... }
反转 if
不能这样用continue
,只能循环使用。 continue
语句将走到循环的末尾并继续下一次迭代,没有循环就没有循环的末尾可去。
您可以使用 else
代替:
if (done) {
// anything to do?
} else {
Console.WriteLine("Not done!");
done = true;
}
如果变量为真无事可做,你可以直接反转表达式:
if (!done) {
Console.WriteLine("Not done!");
done = true;
}
注意:您需要将变量 done
存储在作用域之外。现在您有一个始终设置为 false
的局部变量,因此永远不会跳过代码。
异常是告诉你continue
在这里是无效的。它根本无事可做,也不知道在哪里继续。它旨在在循环的迭代中使用。
我正在尝试将 if 语句与 bool 一起使用,这将使得如果代码 运行s 一旦它不会再次 运行。这是我正在使用的代码。
int random = Program._random.Next(0, 133);
if (random < 33) {
bool done = false;
if(done)
{
continue; // Error is shown for this statement
}
Console.WriteLine("Not done!");
done = true;
}
Visual Studio 显示的错误是:"No enclosing loop out of which to break or continue"。
根据 class/method 要求,您可能会颠倒逻辑:
if (!done)
{
Console.WriteLine("Not done!");
done = true;
}
不能仅在循环内使用 continue。所以你必须没有这个生活:
int random = Program._random.Next(0, 133);
if(random < 33)
{
bool done = false;
if(!done)
{
Console.WriteLine("Not done!");
done = true;
}
}
在这种情况下,您应该使用 if (!done) { ... }
不能这样用continue
,只能循环使用。 continue
语句将走到循环的末尾并继续下一次迭代,没有循环就没有循环的末尾可去。
您可以使用 else
代替:
if (done) {
// anything to do?
} else {
Console.WriteLine("Not done!");
done = true;
}
如果变量为真无事可做,你可以直接反转表达式:
if (!done) {
Console.WriteLine("Not done!");
done = true;
}
注意:您需要将变量 done
存储在作用域之外。现在您有一个始终设置为 false
的局部变量,因此永远不会跳过代码。
异常是告诉你continue
在这里是无效的。它根本无事可做,也不知道在哪里继续。它旨在在循环的迭代中使用。