C# 循环 — 中断与继续

发布于 2024-07-04 03:07:03 字数 313 浏览 14 评论 0原文

在 C#(请随意回答其他语言)循环中,作为离开循环结构并转到循环的方式,breakcontinue 之间有什么区别?下一次迭代?

例子:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //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?

Example:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

梦行七里 2024-07-11 03:07:03

理解这一点的一个非常简单的方法是将“循环”一词放在每个关键字后面。 如果这些术语像日常短语一样阅读,那么现在它们就有意义了。

break循环 - 循环被破坏并停止。

继续循环 - 循环继续执行下一次迭代。

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.

continue loop - loop continues to execute with the next iteration.

青衫负雪 2024-07-11 03:07:03

break 将完全退出循环,continue跳过当前迭代。

例如:

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

    DoSomeThingWith(i);
}

break 将导致循环在第一次迭代时退出 - DoSomeThingWith 将永远不会被执行。

While:

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

    DoSomeThingWith(i);
}

这里继续跳到for循环的下一次迭代,这意味着DoSomeThingWith不会在i == 0时执行。
但循环将继续,并且 DoSomeThingWith 将在 i == 1i == 9 期间执行。

break will exit the loop completely, continue will just skip the current iteration.

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.

While:

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

    DoSomeThingWith(i);
}

Here continue skips to the next iteration of the for-loop, meaning DoSomeThingWith will not execute for i == 0.
But the loop will continue and DoSomeThingWith will be executed for i == 1 to i == 9.

冷…雨湿花 2024-07-11 03:07:03

有不少人不喜欢 breakcontinue。 我最近看到的关于它们的抱怨是 Douglas Crockford 的《JavaScript:The Good Parts》。 但我发现有时使用其中之一确实可以简化事情,特别是如果您的语言不包含 do-whiledo-until 样式的循环。

我倾向于在循环中使用 break 来搜索列表中的内容。 一旦发现,就没有继续下去的意义,所以你还不如退出。

在对列表中的大多数元素执行某些操作时,我使用 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

没有重复,也没有break也需要。

There are more than a few people who don't like break and continue. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. 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.

I tend to use break in loops that are searching a list for something. 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.

The break statement also comes in handy when polling for a valid response from somebody or something. 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:
    Ask a question
    Until the answer is valid

No duplication, and no break needed either.

意犹 2024-07-11 03:07:03

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

break would stop the foreach loop completely, continue would skip to the next DataRow.

能怎样 2024-07-11 03:07:03

break 导致程序计数器跳出最内层循环的范围 工作

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

原理如下

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

continue 跳转到循环末尾。 在 for 循环中, continue 跳转到增量表达式。

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

    printf("%d", i);
}

像这样工作

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

    printf("%d", i);

    CONTINUE:;
}

break causes the program counter to jump out of the scope of the innermost loop

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. In a for loop, continue jumps to the increment expression.

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:;
}
您的好友蓝忘机已上羡 2024-07-11 03:07:03

何时使用中断与继续?

  1. Break - 我们将永远离开循环并永远分手。 再见。

Break

  1. 继续 - 意味着你今天要休息一下,明天再把它全部解决(即跳过当前的迭代)!

继续

(老生常谈的故事 ́́\(ツ)/́́ 和图片只是为了帮助你记住......希望你永远不会忘记)

抱怨警报:

不知道为什么使用这些词。 如果您想跳过迭代,为什么不使用skip一词而不是继续呢? 如果给出正确的名称,整个堆栈溢出问题和成千上万的开发人员都不会感到困惑。)

When to use break vs continue?

  1. Break - We're leaving the loop forever and breaking up forever. Good bye.

Break

  1. Continue - means that you're gonna give today a rest and sort it all out tomorrow (i.e. skip the current iteration)!

Continue

(Corny stories ¯¯\(ツ)/¯¯ and pics solely to help you remember...hopefully you'll never forget)

Gripe Alert:

No idea why those words are being used. If you want to skip the iteration, why not use the word skip instead of continue? This entire Stack overflow question and 1000s of developers would not be confused if the proper name was given.)

情域 2024-07-11 03:07:03

简单答案:

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

Simple answer:

Break exits the loop immediately.
Continue starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)

小矜持 2024-07-11 03:07:03

Break

Break 强制循环立即退出。

继续

这与中断相反。 它没有终止循环,而是立即再次循环,跳过其余代码。

Break

Break forces a loop to exit immediately.

Continue

This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.

假情假意假温柔 2024-07-11 03:07:03

大家都给出了很好的解释。 我仍然发布我的答案只是为了举例说明是否有帮助。

// 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] ";
}

这是输出:

0[已打印] 1[已打印] 2[已打印]

所以 3[已打印] & 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] ";
}

这是输出:

0[已打印] 1[已打印] 2[已打印] 4[已打印]

所以 3[打印] 不会显示,因为当 i == 3 时有继续

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]

So 3[Printed] & 4[Printed] will not be displayed as there is break when 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]

So 3[Printed] will not be displayed as there is continue when i == 3

孤檠 2024-07-11 03:07:03

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

而不是中断/继续,它有中断/下一个,这在循环方面表现相同循环

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

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 很棒,但它也有一些糟糕的极端情况。 这是我使用它多年以来见过的第二糟糕的:-)

Ruby unfortunately is a bit different.
PS: My memory is a bit hazy on this so apologies if I'm wrong

instead of break/continue, it has break/next, which behave the same in terms of loops

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.
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 will jump out of the code that called the block

next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. 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. This is the second worst one I've seen in my years of using it :-)

找个人就嫁了吧 2024-07-11 03:07:03

例如

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 并停止。

用继续替换中断。

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

    Console.WriteLine(i);
}

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

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

By example

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

Prints 1, 2, 3 (on separate lines).

Add a break condition at i = 2

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

    Console.WriteLine(i);
}

Now the loop prints 1 and stops.

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).

Thus, break stops the loop, whereas continue skips to the next iteration.

笨笨の傻瓜 2024-07-11 03:07:03

要完全跳出 foreach 循环,请使用 break

要进入循环中的下一次迭代,请使用继续

如果您循环遍历对象集合(例如数据表中的行)并且正在搜索特定匹配项,则 Break 非常有用,当您找到该匹配项时,无需继续执行剩余的操作行,所以你想突破。

当您完成循环迭代中所需的操作时,继续非常有用。 通常,您会在 if 之后添加继续

To break completely out of a foreach loop, break is used;

To go to the next iteration in the loop, continue is used;

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.

Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.

甜心小果奶 2024-07-11 03:07:03

请让我陈述显而易见的事实:请注意,既不添加中断也不添加继续,将恢复您的程序; 即我陷入了某个错误,然后在记录它之后,我想恢复处理,并且下一行之间还有更多代码任务,所以我就让它失败了。

Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. 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.

思念绕指尖 2024-07-11 03:07:03

如果您不想使用 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
}

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.

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
}
和影子一齐双人舞 2024-07-11 03:07:03

由于此处编写的示例对于理解概念来说非常简单,因此我认为查看所使用的 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,2,2,3,4,5。打印的结果将是:

1,2,3,4,5

为什么? 因为每次用户输入列表中已有的数字时,我们的程序都会忽略它并且不会将列表中已有的数字添加到其中。
现在,如果我们尝试相同的代码,但没有 continue 语句,并且假设用户的输入相同,即 1,2,2,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);
        }

程序会要求用户输入一个数字,直到用户输入“OK”后才会显示结果,为什么?
因为break语句在达到所需条件时完成或停止正在进行的过程。

如果那里没有break语句,程序将继续运行,并且当用户输入“ok”时什么也不会发生。

我建议复制此代码并尝试删除或添加这些语句并亲自查看更改。

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.
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.

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,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.
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.

Now for the Break statement, again I think its the best to show by example. 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.

This is how the break statement is used in this example:

{
            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. Why?
because break statement finished or stops the ongoing process when it has reached the condition needed.

if there was no break statement there, the program would keep running and nothing would happen when the user typed "ok".

I recommend copying this code and trying to remove or add these statements and see the changes yourself.

檐上三寸雪 2024-07-11 03:07:03

至于其他语言:

    '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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文