代码之家  ›  专栏  ›  技术社区  ›  Amr

在foreach内继续

  •  2
  • Amr  · 技术社区  · 17 年前

    在下面的C#代码片段中
    while “a中的循环” 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 “会跳到最开始的地方” 虽然 弗雷奇 这里是否有一个关键字可以使用,或者我应该使用我不喜欢的goto。

    5 回复  |  直到 17 年前
        1
  •  9
  •   Chris Hynes    17 年前

    使用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
        }
    }
    
        2
  •  4
  •   Henk Holterman    17 年前

    下面的内容应该可以做到这一点

    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();
    }
    
        3
  •  2
  •   Mitch Wheat    17 年前

    这个 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();
        }
    }
    
        4
  •  1
  •   erikkallen    17 年前

    使用 goto .

        5
  •  0
  •   andleer    17 年前

    您可以使用“break;”退出最里面的while或foreach。