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' ' ループの先頭にジャンプします。ここで使用するキーワードはありますか、それとも私があまり好きではない goto を使用する必要があります。whileforeach

4

5 に答える 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
    }
}
于 2009-03-07T03:55:40.460 に答える
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();
    }
}
于 2009-03-07T03:55:59.287 に答える