在循环中可以获得控制变量的起始值和结束值的值吗?

时间:2015-11-04 08:49:49

标签: c# for-loop

标题说明了一切,但我会添加一个代码示例,以使其更清晰。

Random r = new Random(); 
for (int i = r.Next(0, 5); i < r.Next(6, 20); i++)
{
    int start = ?
    int end = ?
}

1 个答案:

答案 0 :(得分:4)

在循环外移动开始和结束的声明:

Random r = new Random(); 
int start = r.Next(0, 5);
int end = r.Next(6, 20);
for (int i = start; i < end; i++)
{
    // Your code goes here.

    // If you want to generate a new end criteria for each iteration in a similar way 
    // as your example, you need to add this to the end of the loop:
    end = r.Next(6, 20); 
}

在for循环条件块中运行i < r.Next(6, 20)将为每次迭代生成一个新数字,这可能不是您想要的。