使用哪个循环,for或do/while?

ste*_*ell 4 c# loops

使用C#(或VB.NET)当需要计数器时,应该使用哪个循环(for循环或do/while循环)?

如果循环只应迭代设定次数或设定范围,它会有所不同吗?

场景A - for循环

for (int iLoop = 0; iLoop < int.MaxValue; iLoop++)
{
  //Maybe do work here

  //Test criteria
  if (Criteria)
  {
    //Exit the loop
    break;
  }

  //Maybe do work here
}
Run Code Online (Sandbox Code Playgroud)

好处

  • 计数器被声明为循环的一部分
  • 易于实现计数器范围

缺点

  • 必须使用if离开循环

场景B - do/while循环

int iLoop = 0;
do
{
  //Increment the counter
  iLoop++;

  //Do work here
} while (Criteria);
Run Code Online (Sandbox Code Playgroud)

要么

int iLoop = 0;
while (Criteria)
{
  //Increment the counter
  iLoop++; 

  //Do work here 
}
Run Code Online (Sandbox Code Playgroud)

好处

  • 离开循环是循环结构的一部分
  • 选择在循环块之前或之后进行评估

缺点

  • 必须手动管理计数器

Mar*_*ell 10

为了完整起见,您还可以使用选项D:

for (int iLoop = 0; Criteria; iLoop++)
{
   // work here
}
Run Code Online (Sandbox Code Playgroud)

(Criteria"继续跑"的地方)

for循环中的条件不必涉及iLoop.虽然不寻常,但非常可爱 - 只是工作之前评估.


Fir*_*aad 9

这两个世界的优点如何:

for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
Run Code Online (Sandbox Code Playgroud)

编辑:现在我考虑一下,我想与int.MaxValue进行比较不是标准的一部分,而是模仿无限循环的东西,在这种情况下你可以使用:

for (int iLoop = 0; !Criterea; iLoop++)
Run Code Online (Sandbox Code Playgroud)