在 C# 中使用 Continue 关键字后,无限 while 循环跳过 If 块在未来的迭代中
Infinite while loop skips If blocks in future iterations after Continue keyword used in C#
我的代码有问题。目标是将要求用户输入的过程嵌套在一个无限循环中,该过程仅在提供正确信息或用户单击取消时结束。下面是我的代码:
while (true) { // Loop until correct values are given or process is canceled.
// Ask for list price
#warning this area not tested (two if statements)
if (listPrice < 0) {
if (inputList.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
if (!double.TryParse(inputList.InputValue, out listPrice)) continue; // If value not correct restart loop
else break;
} else return false; // return from method, test failed (if cancel is pressed).
}
if (sewpPrice < 0) {
if (inputSEWP.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
if (!double.TryParse(inputSEWP.InputValue, out sewpPrice)) continue;
else break;
} else return false; // Test automatically failed if exception was thrown trying to read pricing
}
}
然而,当 "continue" 被调用时,整个父 "if" 块("if (listPrice < 0)" 和 "if (sewpPrice < 0)")在所有未来的迭代中都会被跳过。在调用嵌套的 "continue" 语句之前,不会跳过每个特定的 "if" 块。例如,在循环的第二次迭代中,"if (listPrice < 0)" 语句被一起跳过,循环从执行 "if (sewpPrice < 0)" 语句开始。
此外,包含此代码的方法是在 Visual Studio 2015 年通过中级 window 调用的(因为此方法仍在测试中)。
我希望我尽可能清楚,非常感谢任何和所有帮助。
问题不在于 continue
语句,而是误解了 double.TryParse
的工作原理。如果解析失败,它会将 0
存储在您指定的 "out" 参数中。
When this method returns, contains the double-precision floating-point number equivalent of the s parameter, if the conversion succeeded, or zero if the conversion failed.
在while
循环的第二次迭代中,假设两次解析都失败了,那么listPrice
和sewpPrice
都是0
,if
块被跳过。
你需要重新考虑你的逻辑。
我的代码有问题。目标是将要求用户输入的过程嵌套在一个无限循环中,该过程仅在提供正确信息或用户单击取消时结束。下面是我的代码:
while (true) { // Loop until correct values are given or process is canceled.
// Ask for list price
#warning this area not tested (two if statements)
if (listPrice < 0) {
if (inputList.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
if (!double.TryParse(inputList.InputValue, out listPrice)) continue; // If value not correct restart loop
else break;
} else return false; // return from method, test failed (if cancel is pressed).
}
if (sewpPrice < 0) {
if (inputSEWP.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
if (!double.TryParse(inputSEWP.InputValue, out sewpPrice)) continue;
else break;
} else return false; // Test automatically failed if exception was thrown trying to read pricing
}
}
然而,当 "continue" 被调用时,整个父 "if" 块("if (listPrice < 0)" 和 "if (sewpPrice < 0)")在所有未来的迭代中都会被跳过。在调用嵌套的 "continue" 语句之前,不会跳过每个特定的 "if" 块。例如,在循环的第二次迭代中,"if (listPrice < 0)" 语句被一起跳过,循环从执行 "if (sewpPrice < 0)" 语句开始。
此外,包含此代码的方法是在 Visual Studio 2015 年通过中级 window 调用的(因为此方法仍在测试中)。
我希望我尽可能清楚,非常感谢任何和所有帮助。
问题不在于 continue
语句,而是误解了 double.TryParse
的工作原理。如果解析失败,它会将 0
存储在您指定的 "out" 参数中。
When this method returns, contains the double-precision floating-point number equivalent of the s parameter, if the conversion succeeded, or zero if the conversion failed.
在while
循环的第二次迭代中,假设两次解析都失败了,那么listPrice
和sewpPrice
都是0
,if
块被跳过。
你需要重新考虑你的逻辑。