C# 使用 return 退出循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1829593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:12:26  来源:igfitidea点击:

Using return to exit a loop?

c#

提问by GurdeepS

If I write a for, do, or while loop, is it possible to come out of this with the return keyword?

如果我写一个 for、do 或 while 循环,是否可以使用 return 关键字来解决这个问题?

Eg:

例如:

class BreakTest 
{
public static void Main() 
{
  for (int i = 1; i <= 100; i++) 
  {
     if (i == 5) 
        **return;**
     Console.WriteLine(i);
    }
   }
}

I know return can be used to exit if statements so I am curious about this as I have never tried it (and can't access my software to write the code to test this).

我知道 return 可用于退出 if 语句,所以我对此很好奇,因为我从未尝试过(并且无法访问我的软件来编写代码来测试它)。

采纳答案by CesarGon

returnwill exit the current method (Main in your example). Use breakto exit the loop.

return将退出当前方法(在您的示例中为 Main)。使用break退出循环。

回答by Reed Copsey

You cando this. Calling return;will exit Main(). Normally you'd use break;to break out of the for loop instead.

可以这样做。调用return;将退出 Main()。通常,您会使用break;跳出 for 循环来代替。

That being said, it's often considered bad practice to have multiple return locations within a single function. Many developers prefer to have a single return statement (if the method isn't declared with void). This can make the code more easy to follow, from an understandability point of view, and hence easier to maintain and test.

话虽如此,在单个函数中拥有多个返回位置通常被认为是不好的做法。许多开发人员更喜欢使用单个 return 语句(如果该方法未用 声明void)。从可理解性的角度来看,这可以使代码更易于遵循,从而更易于维护和测试。

回答by Dr. Wily's Apprentice

You certainly can do what you're asking. There seem to be 2 camps on whether or not you should. There are some who say that there should only be 1 exit point from a function. They suggest that you should use a flag variable to record that you need to exit (and possibly any data that you need to return), and then return once you've broken out of your loop or reached the end of your if/else trees.

你当然可以做你所要求的。关于您是否应该这样做,似乎有两个阵营。有人说一个函数应该只有 1 个退出点。他们建议您应该使用标志变量来记录您需要退出的信息(可能还有您需要返回的任何数据),然后在您退出循环或到达 if/else 树的末尾时返回.

Personally, I have no problem with multiple exit points from a function, as long as they are symmetric. What do I mean by "symmetric"? Well, if I am going to return from inside of a loop, then I also want to return at the end of the loop (in case I never reach the condition in the loop that would cause me to return early). If I'm inside of a complex if/else heirarchy and I return from within one of the cases, then I should return from within all of them.

就我个人而言,我对一个函数的多个退出点没有问题,只要它们是对称的。我所说的“对称”是什么意思?好吧,如果我要从循环内部返回,那么我也想在循环结束时返回(以防我永远不会达到循环中会导致我提前返回的条件)。如果我处于复杂的 if/else 层次结构中并且我从其中一个案例中返回,那么我应该从所有案例中返回。

Here are some quick examples of how I prefer to write my code:

以下是一些关于我更喜欢​​如何编写代码的快速示例:

    public string Search(IEnumerable<string> values)
    {
        foreach(string value in values)
        {
            if(SomeArbitraryCondition())
                return value;
        }

        return null;
    }

    public int PerformAction()
    {
        if (SomeArbitraryCondition())
        {
            if (SomeArbitraryCondition())
            {
                return 1;
            }
            else
            {
                return 2;
            }
        }
        else
        {
            if (SomeArbitraryCondition())
            {
                return 3;
            }
            else
            {
                return 4;
            }
        }
    }

This isn't really a hard and fast rule that I've thought much about, but it's simply the way that I prefer to write it because it seems cleanest to me. In some cases, it makes more sense to use a flag variable and just return in one place.

这并不是我想太多的硬性规定,但这只是我更喜欢的编写方式,因为它对我来说似乎最干净。在某些情况下,使用标志变量并只在一个地方返回更有意义。

    public string Search(IEnumerable<string> values)
    {
        string found = null;
        foreach(string value in values)
        {
            if(SomeArbitraryCondition())
                found = value;
        }

        return found;
    }

    public int PerformAction()
    {
        int state;
        if (SomeArbitraryCondition())
        {
            if (SomeArbitraryCondition())
            {
                state = 1;
            }
            else
            {
                state = 2;
            }
        }
        else
        {
            if (SomeArbitraryCondition())
            {
                state = 3;
            }
            else
            {
                state = 4;
            }
        }

        return state;
    }

回答by Victor van Duynen

Answer way overdue but return;will exit your whole method (so out of your loop, too) if its return type is void. If it's not, it just won't compile unless your return the method's type.

回答方式逾期,但return;如果其返回类型为空,则会退出您的整个方法(因此也退出您的循环)。如果不是,除非您返回方法的类型,否则它将无法编译。

回答by mudrak patel

Keep these in mind:

请记住以下几点:

  1. You CAN DO this, but not recommended because it automatically exits from the current method of execution.
  2. Not useful when other statements after the loop are mandatory no matter the conditions (due to it's behaviour stated in the 1st point).
  3. Can create a ripple effect in your program i.e. attempt to solve one error/bug/fault gives rise to many new. This makes debugging a bit complex.
  1. 您可以这样做,但不建议这样做,因为它会自动退出当前的执行方法。
  2. 当循环后的其他语句无论条件如何都是强制性的(由于它在第一点中说明的行为)时,它没有用。
  3. 可以在您的程序中产生涟漪效应,即尝试解决一个错误/错误/故障会产生许多新的错误。这使得调试有点复杂。