質問

次のC#コードスニペット
foreach 」ループ内に「 while 」ループがあり、特定のタイミングで「 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 'は、 ' foreach 'ループではなく、 ' while 'ループの先頭にジャンプします。 ここで使用するキーワードはありますか、それとも本当に気に入らないgotoを使用する必要があります。

役に立ちましたか?

解決

次のトリックを実行する必要があります

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();
}

他のヒント

breakキーワードを使用します。これにより、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; キーワードはループを終了します:

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();
    }
}

goto を使用します。

(この反応に人々は怒っていると思いますが、他のすべてのオプションよりも読みやすいと思います。)

" break;"を使用できます最も内側のwhileまたはforeachを終了します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top