使用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)
好处
缺点
场景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.虽然不寻常,但非常可爱 - 只是在工作之前评估.
这两个世界的优点如何:
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)