当使用C#中的“继续”关键字 [英] When to use the 'continue' keyword in C#

查看:131
本文介绍了当使用C#中的“继续”关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我正在经历一个开源项目,虽然我一直在开发数年的.NET,我还没有穿过的 继续 之前的关键字。

Recently, I was going through an open-source project and although I have been developing for several years in .NET, I hadn't stumbled across the continue keyword before.

问:什么是一些最佳做法或将受益于使用继续关键字的地方?有没有可能是我见过的一个原因是previously?

Question: What are some best practices or areas that would benefit from using the continue keyword? Is there a reason I might not have seen it previously?

推荐答案

您用它来立即退出本次循环,开始下一个(如果适用)。

You use it to immediately exit the current loop iteration and begin the next, if applicable.

foreach (var obj in list)
{
    continue;

    var temp = ...; // this code will never execute
}

A 继续通常依赖于一个条件,并且条件通常可以代替使用的继续 ;

A continue is normally tied to a condition, and the condition could usually be used in place of the continue;

foreach (var obj in list)
{ 
    if (condition)
       continue;

    // code
} 

可能只是写成

Could just be written as

foreach (var obj in list)
{
    if (!condition)
    {
        // code
    }
}

继续变得更有吸引力,如果你可能有几个层次的嵌套,如果逻辑循环中。 A 继续代替嵌套可能使code更具可读性。当然,重构循环和条件语句插入适当的方法也使循环更加易读。

continue becomes more attractive if you might have several levels of nested if logic inside the loop. A continue instead of nesting might make the code more readable. Of course, refactoring the loop and the conditionals into appropriate methods would also make the loop more readable.

这篇关于当使用C#中的“继续”关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆