【发布时间】:2009-08-25 10:16:10
【问题描述】:
使用 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
}
优势
- 计数器被声明为循环的一部分
- 易于实施计数器范围
缺点
- 必须使用 if 才能离开循环
场景 B - do/while 循环
int iLoop = 0;
do
{
//Increment the counter
iLoop++;
//Do work here
} while (Criteria);
或
int iLoop = 0;
while (Criteria)
{
//Increment the counter
iLoop++;
//Do work here
}
优势
- 离开循环是循环结构的一部分
- 选择在循环块之前或之后进行评估
缺点
- 必须手动管理计数器
【问题讨论】:
-
我想知道为什么每个人都在他们的答案中不断复制
iLoop < int.MaxValue部分,而这显然总是正确的...... -
应该更改标题以添加“while”循环
-
@Luis Filipe - While 循环在标题中!
-
@Stevo3000:我建议“使用哪个循环,for、While 还是 do/while?”
-
@Luis Filipe - 问题是指做/同时表示做或同时。我认为没有任何真正需要分开他们。