简体   繁体   English

C# 循环 - 中断与继续

[英]C# loop - break vs. continue

In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?在 C#(其他语言可以随意回答)循环中,作为离开循环结构并进入下一次迭代的手段, breakcontinue之间有什么区别?

Example:例子:

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

break will exit the loop completely, continue will just skip the current iteration. break将完全退出循环, continue跳过当前迭代。

For example:例如:

for (int i = 0; i < 10; i++) {
    if (i == 0) {
        break;
    }

    DoSomeThingWith(i);
}

The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed.中断将导致循环在第一次迭代时退出 - DoSomeThingWith将永远不会被执行。 This here:这里:

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;
    }

    DoSomeThingWith(i);
}

Will not execute DoSomeThingWith for i = 0 , but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9 .不会为i = 0执行DoSomeThingWith ,但循环将继续并且DoSomeThingWith将在i = 1i = 9

A really easy way to understand this is to place the word "loop" after each of the keywords.理解这一点的一个非常简单的方法是在每个关键字之后放置“循环”一词。 The terms now make sense if they are just read like everyday phrases.如果这些术语只是像日常短语一样阅读,那么它们现在就有意义了。

break loop - looping is broken and stops. break循环 - 循环中断并停止。

continue loop - loop continues to execute with the next iteration. continue循环 - 循环继续执行下一次迭代。

break causes the program counter to jump out of the scope of the innermost loop break导致程序计数器跳出最内层循环的范围

for(i = 0; i < 10; i++)
{
    if(i == 2)
        break;
}

Works like this像这样工作

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto BREAK;
}
BREAK:;

continue jumps to the end of the loop. continue跳到循环的末尾。 In a for loop, continue jumps to the increment expression.在 for 循环中, continue 跳转到增量表达式。

for(i = 0; i < 10; i++)
{
    if(i == 2)
        continue;

    printf("%d", i);
}

Works like this像这样工作

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto CONTINUE;

    printf("%d", i);

    CONTINUE:;
}

I used to always get confused whether I should use break, or continue.我曾经总是对我应该使用 break 还是 continue 感到困惑。 This is what helps me remember:这有助于我记住:

When to use break vs continue?何时使用中断与继续?

  1. Break - it's like breaking up.分手- 就像分手一样。 It's sad, you guys are parting.很遗憾,你们要分开了。 The loop is exited.退出循环。

休息

  1. Continue - means that you're gonna give today a rest and sort it all out tomorrow (ie skip the current iteration)!继续- 意味着你今天要休息一下,明天把它全部解决(即跳过当前的迭代)!

继续

break将完全停止foreach循环, continue将跳到下一个DataRow

There are more than a few people who don't like break and continue .有不少人不喜欢breakcontinue The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford.我最近看到的关于它们的抱怨是在JavaScript: Douglas Crockford 的The Good Parts 中 But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a do-while or do-until style of loop.但我发现有时使用其中之一确实可以简化事情,特别是如果您的语言不包含do-whiledo-until风格的循环。

I tend to use break in loops that are searching a list for something.我倾向于在循环中使用break来搜索列表。 Once found, there's no point in continuing, so you might as well quit.一旦发现,继续下去没有意义,所以你最好退出。

I use continue when doing something with most elements of a list, but still want to skip over a few.我在处理列表中的大多数元素时使用continue ,但仍然想跳过一些。

The break statement also comes in handy when polling for a valid response from somebody or something.在轮询某人或某事的有效响应时, break语句也派上用场。 Instead of:代替:

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

You could eliminate some duplication and use:您可以消除一些重复并使用:

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

The do-until loop that I mentioned before is the more elegant solution for that particular problem:我之前提到的do-until循环是针对该特定问题的更优雅的解决方案:

Do:
    Ask a question
    Until the answer is valid

No duplication, and no break needed either.没有重复,也不需要break

All have given a very good explanation.都给出了很好的解释。 I am still posting my answer just to give an example if that can help.我仍然发布我的答案只是为了举例说明是否有帮助。

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:这是输出:

0[Printed] 1[Printed] 2[Printed] 0[印刷] 1[印刷] 2[印刷]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3所以 3[Printed] & 4[Printed] 不会显示,因为当 i == 3 时有中断

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:这是输出:

0[Printed] 1[Printed] 2[Printed] 4[Printed] 0[印刷] 1[印刷] 2[印刷] 4[印刷]

So 3[Printed] will not be displayed as there is continue when i == 3所以 3[Printed] 不会显示,因为当 i == 3 时有 continue

Break休息

Break forces a loop to exit immediately. Break 强制循环立即退出。

Continue继续

This does the opposite of break.这与 break 正好相反。 Instead of terminating the loop, it immediately loops again, skipping the rest of the code.它没有终止循环,而是立即再次循环,跳过其余代码。

By example举例

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

Prints 1, 2, 3 (on separate lines).打印 1、2、3(在单独的行上)。

Add a break condition at i = 2在 i = 2 处添加中断条件

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

    Console.WriteLine(i);
}

Now the loop prints 1 and stops.现在循环打印 1 并停止。

Replace the break with a continue.用继续替换中断。

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

    Console.WriteLine(i);
}

Now to loop prints 1 and 3 (skipping 2).现在循环打印 1 和 3(跳过 2)。

Thus, break stops the loop, whereas continue skips to the next iteration.因此, break停止循环,而continue跳到下一次迭代。

Simple answer:简单回答:

Break exits the loop immediately. Break立即退出循环。
Continue starts processing the next item.继续开始处理下一个项目。 (If there are any, by jumping to the evaluating line of the for/while) (如果有的话,跳到 for/while 的求值行)

Ruby unfortunately is a bit different.不幸的是,Ruby 有点不同。 PS: My memory is a bit hazy on this so apologies if I'm wrong PS:我的记忆有点模糊所以如果我错了请道歉

instead of break/continue, it has break/next, which behave the same in terms of loops它有 break/next,而不是 break/continue,它们在循环方面的行为相同

Loops (like everything else) are expressions, and "return" the last thing that they did.循环(和其他一切一样)是表达式,并且“返回”它们所做的最后一件事。 Most of the time, getting the return value from a loop is pointless, so everyone just does this大多数时候,从循环中获取返回值是没有意义的,所以每个人都这样做

a = 5
while a < 10
    a + 1
end

You can however do this但是你可以这样做

a = 5
b = while a < 10
    a + 1
end # b is now 10

HOWEVER, a lot of ruby code 'emulates' a loop by using a block.然而,许多 ruby​​ 代码通过使用块来“模拟”循环。 The canonical example is典型的例子是

10.times do |x|
    puts x
end

As it is much more common for people to want to do things with the result of a block, this is where it gets messy.由于人们想要用块的结果做事更为常见,这就是它变得混乱的地方。 break/next mean different things in the context of a block. break/next 在块的上下文中意味着不同的东西。

break will jump out of the code that called the block break 会跳出调用块的代码

next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. next 将跳过块中的其余代码,并将您指定的内容“返回”给块的调用者。 This doesn't make any sense without examples.没有例子,这没有任何意义。

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.

So yeah.是的。 Ruby is awesome, but it has some awful corner-cases. Ruby 很棒,但它也有一些糟糕的情况。 This is the second worst one I've seen in my years of using it :-)这是我使用它多年以来见过的第二差的:-)

Please let me state the obvious: note that adding neither break nor continue, will resume your program;请让我说明一个明显的问题:注意,既不添加 break 也不添加 continue,将恢复您的程序; ie I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.即我因为某个错误而被困,然后在记录它之后,我想继续处理,并且在下一行之间有更多的代码任务,所以我就让它失败了。

To break completely out of a foreach loop, break is used;要完全脱离 foreach 循环,可以使用break

To go to the next iteration in the loop, continue is used;要进入循环中的下一次迭代,请使用continue

Break is useful if you're looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there's no need to continue through the remaining rows, so you want to break out.如果您循环遍历对象集合(如数据表中的行)并且您正在搜索特定匹配项,则Break很有用,当您找到该匹配项时,无需继续遍历剩余的行,因此您想中断出去。

Continue is useful when you have accomplished what you need to in side a loop iteration.当您在循环迭代中完成所需的操作时, Continue很有用。 You'll normally have continue after an if .您通常会在if之后继续

if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.如果你不想使用break你只需增加 I 的值,这样它就会使迭代条件为假并且循环不会在下一次迭代中执行。

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
}

As for other languages:至于其他语言:

'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

Since the example written here are pretty simple for understanding the concept I think it's also a good idea to look at the more practical version of the continue statement being used.由于此处编写的示例对于理解概念非常简单,因此我认为查看正在使用的continue 语句的更实用版本也是一个好主意。 For example:例如:

we ask the user to enter 5 unique numbers if the number is already entered we give them an error and we continue our program.如果已经输入了数字,我们会要求用户输入 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);
            }


        }

lets say the users input were 1,2,2,2,3,4,5.the result printed would be:假设用户输入是 1,2,2,2,3,4,5.the result 打印将是:

1,2,3,4,5

Why?为什么? because every time user entered a number that was already on the list, our program ignored it and didn't add what's already on the list to it.因为每次用户输入一个已经在列表中的数字时,我们的程序都会忽略它,并且不会将列表中已有的内容添加到其中。 Now if we try the same code but without continue statement and let's say with the same input from the user which was 1,2,2,2,3,4,5.现在,如果我们尝试相同的代码但没有 continue 语句,并且假设来自用户的相同输入是 1,2,2,2,3,4,5。 the output would be :输出将是:

1,2,2,2,3,4

Why?为什么? because there was no continue statement to let our program know it should ignore the already entered number.因为没有 continue 语句让我们的程序知道它应该忽略已经输入的数字。

Now for the Break statement , again I think its the best to show by example.现在对于Break 语句,我再次认为最好通过示例来展示。 For example:例如:

Here we want our program to continuously ask the user to enter a number.在这里,我们希望我们的程序不断地要求用户输入一个数字。 We want the loop to terminate when the user types “ok" and at the end Calculate the sum of all the previously entered numbers and display it on the console.我们希望循环在用户键入“ok”时终止,并在最后计算所有先前输入的数字的总和并将其显示在控制台上。

This is how the break statement is used in this example:这是本示例中使用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);
        }

The program will ask the user to enter a number till the user types "OK" and only after that, the result would be shown.程序会要求用户输入一个数字,直到用户输入“OK”,然后才会显示结果。 Why?为什么? because break statement finished or stops the ongoing process when it has reached the condition needed.因为 break 语句在达到所需条件时完成或停止正在进行的过程。

if there was no break statement there, the program would keep running and nothing would happen when the user typed "ok".如果那里没有 break 语句,程序将继续运行,并且当用户输入“ok”时什么也不会发生。

I recommend copying this code and trying to remove or add these statements and see the changes yourself.我建议复制此代码并尝试删除或添加这些语句并自己查看更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM