我可以在for循环的增量中放入特定条件语句吗?

时间:2019-11-08 22:49:01

标签: c#

例如:

for (int i = 0; i < 9; i++ && (a specific condition to the incremented variable))

这将用于在虚假无穷远处停止循环,直到达到上述条件为止。

这点是要让循环仍继续执行其操作,同时停止i变量的增加,直到满足条件为止。例如,如果(“另一个变量” <9),那么我可以使其为正常增量。在其他情况下,如果不满足该条件,则i不会递增,但是循环仍将一步一步地执行指令。

5 个答案:

答案 0 :(得分:3)

您可以实现

for (int i = 0; i < 9; i++ && (a specific condition to the incremented variable))

for (int i = 0; i < 9; i = (a specific condition to the incremented variable) ? i + 1 : i)

但这违反了for循环的一般目的和意图。这只会使您的测试人员,审阅者和其他编码人员感到困惑。

而且,并非每次都如此,这将通过每次添加一个范围检查来使CLR优化器放弃并放慢myArray[i]的速度。

答案 1 :(得分:2)

我认为您正在查看的内容如下:

var counter = 0;
var otherCondition = 15;

while (counter < 9)
{
    if (otherCondition < 9)
    {
        counter++;
    }
    // Do other stuff
}

您就像在counter循环中一样,从0开始for,并在到达9时终止。但是只有在满足其他条件时才会增加。

答案 2 :(得分:1)

我认为合适的控制结构流是一个嵌套循环,内部循环“固定”到无穷大。

for (int i = 0; i < 9; i++ )
{
    do
    {
        Foo();
    } while (!condition)
}

答案 3 :(得分:0)

i += (true/false) ? 1 : 0呢?

for (int i = 0; i < 9; i += (a specific condition to the incremented variable) ? 1 : 0)

例如:

var n = 0;
for (int i = 0; i < 9; i += (n++%2==0) ? 1 : 0) {
    Console.WriteLine(i);
}

话虽如此,它使代码不必要地难以阅读和理解。

以下两个例子更加清楚。

int met = 0;
while(true) 
{
  if(a specific condition to the incremented variable) met++;
  if(met >= 9) break;
}

var met = 0;
while( met < 9 ) 
{
  if(a specific condition to the incremented variable) met++;
}

答案 4 :(得分:-1)

在这种情况下,我认为while会更有用:

int i = 0;
while (i < 9)
{
    if (condition)
        i++;
}