在C#循环中,中断和继续作为离开循环结构并进入下一次迭代的方法有什么区别?

例子:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}

当前回答

何时使用中断与继续?

分手-我们将永远离开循环,永远分手。再见。

继续-意味着你今天要休息一下,明天再把它整理好(即跳过当前迭代)!

(Corny故事)\(ツ)/“”和图片,但希望能帮助你记住。

抓握提醒:不知道为什么要使用这些词。如果您想跳过迭代,为什么不使用skip而不是continue?如果给出了正确的名称,整个堆栈溢出问题和1000名开发人员不会感到困惑。)

其他回答

举个例子

foreach(var i in Enumerable.Range(1,3))
{
    Console.WriteLine(i);
}

打印1、2、3(在单独的行上)。

在i=2时添加中断条件

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        break;

    Console.WriteLine(i);
}

现在循环打印1并停止。

用continue替换中断。

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        continue;

    Console.WriteLine(i);
}

现在循环打印1和3(跳过2)。

因此,break会停止循环,而continue会跳到下一次迭代。

简单答案:

Break立即退出循环。继续开始处理下一项。(如果有,跳转到for/while的评估行)

有很多人不喜欢休息和继续。我最近看到的关于他们的投诉是在道格拉斯·克罗克福德的《JavaScript:好零件》中。但我发现,有时使用其中一个确实会简化事情,特别是当您的语言不包含do-while或do-wil循环样式时。

我倾向于使用插入循环来搜索列表中的内容。一旦被发现,就没有继续下去的意义,所以你最好退出。

我使用continue来处理列表中的大多数元素,但仍然想跳过一些元素。

当轮询某人或某物的有效响应时,break语句也很有用。而不是:

Ask a question
While the answer is invalid:
    Ask the question

您可以消除一些重复并使用:

While True:
    Ask a question
    If the answer is valid:
        break

我之前提到的do until循环是该特定问题的更优雅的解决方案:

Do:
    Ask a question
    Until the answer is valid

不需要重复,也不需要中断。

不幸的是,Ruby有点不同。PS:我的记忆有点模糊,所以如果我错了,请道歉

它有break/next,而不是break/content,它们在循环方面的行为相同

循环(和其他一切一样)是表达式,并“返回”它们所做的最后一件事。大多数时候,从循环中获取返回值是没有意义的,所以每个人都这样做

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将跳出调用块的代码

接下来将跳过块中的其余代码,并将您指定的内容“返回”给块的调用者。没有例子,这毫无意义。

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很棒,但它有一些可怕的角落。这是我多年来用过的第二糟糕的:-)

至于其他语言:

    '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