跳出嵌套循环 [英] Breaking out of a nested loop

查看:38
本文介绍了跳出嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个嵌套在另一个循环中的 for 循环,我怎样才能以最快的方式有效地退出两个循环(内部和外部)?

If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way?

我不想必须使用布尔值然后不得不说转到另一个方法,而只想在外循环之后执行第一行代码.

I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop.

有什么快速而好的方法可以解决这个问题?

What is a quick and nice way of going about this?

我认为异常并不便宜/应该只在真正异常的情况下抛出等等.因此,从性能的角度来看,我认为这个解决方案不是很好.

I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective.

我认为利用 .NET 中的新功能(匿名方法)来做一些非常基础的事情是不对的.

I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.

推荐答案

好吧,goto,但这很丑陋,而且并不总是可行.您还可以将循环放入一个方法(或匿名方法)中,然后使用 return 退出回到主代码.

Well, goto, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return to exit back to the main code.

    // goto
    for (int i = 0; i < 100; i++)
    {
        for (int j = 0; j < 100; j++)
        {
            goto Foo; // yeuck!
        }
    }
Foo:
    Console.WriteLine("Hi");

对比:

// anon-method
Action work = delegate
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits anon-method
        }
    }
};
work(); // execute anon-method
Console.WriteLine("Hi");

<小时>

请注意,在 C# 7 中我们应该得到本地函数",这(语法 tbd 等)意味着它应该像这样工作:


Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:

// local function (declared **inside** another method)
void Work()
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits local function
        }
    }
};
Work(); // execute local function
Console.WriteLine("Hi");

这篇关于跳出嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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