我有以下而声明 -
while ((!testString.Contains("hello")) && (NewCount != OldCount) && (attemptCount < 100))
{
//do stuff (steps out too early)
}
即使所有条件都没有得到满足,这也会逐步退出声明。
我试图像 -
那样减少它while (!testString.Contains("hello"))
{
// this works and steps out when it should
}
例如,当hello
存在时,这会逐步消失。我也尝试将其更改为 OR 语句,该语句将问题转移为永不执行语句。
Addint && (NewCount != OldCount) && (attemptCount < 100))
条件导致此行为如何解决此问题?
答案 0 :(得分:3)
即使在所有条件下,这也是出于声明 没有得到满足。
要实现这一点,您需要指定逻辑OR
(||
)。
例如:
while ((!testString.Contains("hello")) || (NewCount != OldCount) || (attemptCount < 100))
{
//while at least one those conditions is true, loop will work
}
这意味着内部循环需要引入安全检查,需要,条件不是更真实,而循环仍在执行。
答案 1 :(得分:2)
作为Tigran答案的补充。通常(为了避免混淆复杂条件)将条件推入循环可能是有用的:
while (true) { // loop forever unless:
if (testString.Contains("hello")) // ...test string contains "hello"
break;
if (NewCount == OldCount) // ...counts are equal
break;
if (attemptCount >= 100) // ... too many attempts
break;
// ...it's easy to add conditions (as well as comment them out) when you have them
// Loop body
}