【问题标题】:Infinite while loop skips If blocks in future iterations after Continue keyword used in C#在 C# 中使用 Continue 关键字之后,无限 while 循环会跳过未来迭代中的 If 块
【发布时间】:2016-03-24 15:39:10
【问题描述】:

我的代码有问题。目标是将询问用户输入的过程嵌套在一个无限循环中,该循环仅在提供正确信息或用户单击取消时结束。以下是我的代码:

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
                        }
                    }

但是,当调用“继续”时,整个父“if”块(“if (listPrice

此外,包含此代码的方法通过 Visual Studio 2015 中的中间窗口调用(因为此方法仍在测试中)。

我希望我尽可能清楚,非常感谢任何和所有帮助。

【问题讨论】:

    标签: c# if-statement infinite-loop continue


    【解决方案1】:

    问题不在于continue 语句,而在于对double.TryParse 工作原理的误解。如果解析失败,它会将0 存储在您指定的“out”参数中。

    当此方法返回时,如果转换成功,则包含与 s 参数等效的双精度浮点数,如果转换失败则返回零。

    在while 循环的第二次迭代中,假设两个解析都失败了,那么listPrice 和sewpPrice 都是0,并跳过if 块。

    你需要重新思考你的逻辑。

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2016-06-05
      • 1970-01-01
      • 2014-10-30
      • 2023-04-07
      • 2016-10-22
      相关资源
      最近更新 更多