C#(欢迎回答其他语言)循环中,使用break
和continue
作为离开循环结构并进入下一次迭代的方式有什么区别?
例如:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
C#(欢迎回答其他语言)循环中,使用break
和continue
作为离开循环结构并进入下一次迭代的方式有什么区别?
例如:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
很遗憾,Ruby有点不同。
它使用break/next代替break/continue,在循环方面的行为相同。
循环(像其他所有东西一样)都是表达式,并且“返回”它们最后执行的内容。大多数情况下,从循环中获取返回值是无意义的,因此每个人都只是这样做。
a = 5
while a < 10
a + 1
end
a = 5
b = while a < 10
a + 1
end # b is now 10
然而,很多Ruby代码通过使用块来“模拟”循环。经典的例子是:
10.times do |x|
puts x
end
由于大多数人更希望通过块的结果来完成任务,这就使得事情变得混乱。
在块的上下文中,break/next有不同的含义。
break将跳出调用块的代码。
next将跳过块中剩余的代码,并将你指定的内容“返回”给块的调用者。如果没有示例,这是没有意义的。
def timesten
10.times{ |t| puts yield t }
end
timesten do |x|
x * 2
end
# will print
2
4
6
8 ... and so on
timesten do |x|
break
x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped
timesten do |x|
break 5
x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5
timesten do |x|
next 5
x * 2
end
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.
所以说,Ruby 真的很棒,但它也有一些令人不爽的地方。这是我使用 Ruby 多年来看到的第二个最糟糕的问题 :-)
如果您不想使用 break,您可以通过增加I的值来使迭代条件变为false,这样循环就不会在下一次迭代时执行。
for(int i = 0; i < list.Count; i++){
if(i == 5)
i = list.Count; //it will make "i<list.Count" false and loop will exit
}
break
就是为了这个目的而存在的,因此为了避免使用关键字而做出更加混乱的事情是愚蠢的。 - Mike Christiansen由于这里的示例非常简单易懂,以便理解概念,我认为查看更多实用版本的continue语句也是一个好主意。
例如:
我们要求用户输入5个唯一数字,如果该数字已经输入,则给出错误提示并继续执行程序。
static void Main(string[] args)
{
var numbers = new List<int>();
while (numbers.Count < 5)
{
Console.WriteLine("Enter 5 uniqe numbers:");
var number = Convert.ToInt32(Console.ReadLine());
if (numbers.Contains(number))
{
Console.WriteLine("You have already entered" + number);
continue;
}
numbers.Add(number);
}
numbers.Sort();
foreach(var number in numbers)
{
Console.WriteLine(number);
}
}
1,2,3,4,5
1,2,2,2,3,4
为什么?因为没有continue语句告诉我们的程序应该忽略已经输入的数字。
现在来看Break语句,我认为最好的方式是通过示例来说明。例如:
这里我们希望程序不断地要求用户输入一个数字。当用户输入“ok”时,我们希望循环终止,并在最后计算所有先前输入数字的总和并在控制台上显示它。
以下是此示例中使用break语句的方法:
{
var sum = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var input = Console.ReadLine();
if (input.ToLower() == "ok")
break;
sum += Convert.ToInt32(input);
}
Console.WriteLine("Sum of all numbers is: " + sum);
}
至于其他编程语言:
'VB
For i=0 To 10
If i=5 then Exit For '= break in C#;
'Do Something for i<5
next
For i=0 To 10
If i=5 then Continue For '= continue in C#
'Do Something for i<>5...
Next
continue;
会停止处理当前的行并继续处理集合中的下一行。另一方面,break;
将完全离开foreach
语句,并且剩余的行将永远不会被处理。 - Jeppe Stig Nielsen