在foreach循环中继续执行while循环

3
在下面的C#代码片段中,我有一个嵌套的'while'循环和一个'foreach'循环,当发生某些条件时,我希望跳到下一个'foreach'项。
foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}

'continue'会跳转到'while'循环的开头,而不是'foreach'循环的开头。这里是否有一个关键字可以使用,或者我只能使用我不太喜欢的goto?
5个回答

9

使用关键字“break”。这将退出while循环并继续执行外部的内容。由于在while之后没有其他内容,它会循环到foreach循环中的下一个项目。

实际上,仔细查看您的示例,您实际上想要能够在不退出while的情况下推进for循环。您无法在foreach循环中这样做,但您可以将foreach循环拆分为它实际自动化的内容。在.NET中,foreach循环实际上是在IEnumerable对象(即您的this.ObjectNames对象)上调用.GetEnumerator()的结果。

foreach循环基本上是这样的:

IEnumerator enumerator = this.ObjectNames.GetEnumerator();

while (enumerator.MoveNext())
{
    string objectName = (string)enumerator.Value;

    // your code inside the foreach loop would be here
}

一旦您拥有了这个结构,您可以在while循环中调用enumerator.MoveNext()来前进到下一个元素。因此,您的代码将变为:

IEnumerator enumerator = this.ObjectNames.GetEnumerator();

while (enumerator.MoveNext())
{
    while (this.ResumeWhileLoop())
    {
        if (this.MoveToNextObject())
        {
            // advance the loop
            if (!enumerator.MoveNext())
                // if false, there are no more items, so exit
                return;
        }

        // do your stuff
    }
}

很抱歉,我最初添加的代码片段不是很准确。还有更多需要跳过的代码。使用break语句无法解决问题。 我已经更新了代码片段,使其更加准确。 - Amr
2
虽然我喜欢你的答案,因为它解决了问题而不添加额外的逻辑;但我认为这不是一个好的解决方案。我不知道在 OP 的情况下如何做到这一点,但是以这种方式构建代码,使得首先不需要这种疯狂的逻辑,将是最好的解决方案。 - user19302
我建议重新考虑问题,绕过 for 循环中的逻辑。但我也认为了解像 foreach 这样的高级构造是很好的,而且这种方法确实解决了手头的问题。 - Chris Hynes

4
以下内容应该能解决问题。
foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
            break;
        }
    }
    if (! this.boolValue) continue; // continue foreach

    this.ExecuteSomeOtherCode();
}

2
break; 关键字将退出循环:
foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        if (this.MoveToNextObject())
        {
            break;
        }
        this.boolValue = this.ResumeWhileLoop();
    }
}

1

使用 goto

(我猜人们会对这个回答感到生气,但我绝对认为它比其他选项更易读。)


0

您可以使用"break;"来退出最内层的while或foreach循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接