c#foreach语句中break 和continue的区别
- 在foreach中使用break时,会结束整个foreach循环;
- 在foreach中使用 continue时,会结束当前的循环,继续下一轮的循环,并不会跳出整个循环;
Demo:
public static void ContinueAndBreakInForeach()
{
List<int> list = new List<int>();
for (int i = 0; i < 5; i++)
{
list.Add(i);
}
Console.WriteLine("break in foreach statement \n");
foreach (int item in list)
{
if (item == 2)
{
break;
}
else
{
Console.Write(item + "\t");
}
}
Console.WriteLine("\n continue in foreach statement");
foreach (int item in list)
{
if (item == 2)
{
continue;
}
else
{
Console.Write(item + "\t");
}
}
}
结果: