1

for loops以下の2つの出力が異なる出力を生成する理由を理解できる人はいますか?

私の目には同じですが、元Dictionaryのオブジェクトfor loopはそのメンバーの 9 つすべてを出力しますが、Queueオブジェクトfor loopは最初の 5 つだけを出力します。

void test()
{
        Dictionary<int, string> d = new Dictionary<int, string>();

        d.Add(0, "http://example.com/1.html");
        d.Add(1, "http://example.com/2.html");
        d.Add(2, "http://example.com/3.html");
        d.Add(3, "http://example.com/4.html");
        d.Add(4, "http://example.com/5.html");
        d.Add(5, "http://example.com/6.html");
        d.Add(6, "http://example.com/7.html");
        d.Add(7, "http://example.com/8.html");
        d.Add(8, "http://example.com/9.html");

        Queue<KeyValuePair<int, string>> requestQueue = new Queue<KeyValuePair<int, string>>();

        // build queue
        foreach (KeyValuePair<int, string> dictionaryListItem in d)
        {
            requestQueue.Enqueue(dictionaryListItem);
            Console.WriteLine(dictionaryListItem.Value);
        }

        Console.WriteLine("          ");

        for (int i = 0; i < requestQueue.Count; i++)
        {
            Console.WriteLine(requestQueue.Peek().Value);
            requestQueue.Dequeue();
        }
}
4

3 に答える 3

6

ループの前にカウントを保存する必要があります。

var count = requestQueue.Count;
for (int i = 0; i < count; i++)
{
    Console.WriteLine(requestQueue.Peek().Value);
    requestQueue.Dequeue();
}

その理由は、for ループの各反復で評価されるためです。

最初の反復の開始時requestQueue.Countは 9iです0
2 回目の反復:requestQueue.Countは 8、i1です。
3 回目の反復:requestQueue.Countは 7、i2です。
4 回目の反復:requestQueue.Countは 6、i3です。
5 回目の反復:requestQueue.Countは 5、i4です。
6 回目の反復:requestQueue.Countは 4、i5です。--> ループを終了します。

注:はキュー内の最初のアイテムを削除して呼び出し元に返すCountため、反復ごとにキューのサイズが縮小されます。Queue.Dequeue

于 2013-02-12T14:15:37.047 に答える
3

おそらく、while-loop代わりにこれを使用することをお勧めします。これは、ここでより意味があります。

while (requestQueue.Count > 0)
{
    Console.WriteLine(requestQueue.Peek().Value);
    requestQueue.Dequeue();
}

あなたの問題は、プロパティを減らす最初のアイテムを削除することfor-loopです。それが「途中で」止まる理由です。Queue.DequeueCount

ループ変数iはまだ増加していますが、Count減少しています。

于 2013-02-12T14:17:33.060 に答える
1

requestQueue.Dequeue() を呼び出すたびに、requestQueue 内のアイテムの量を変更しているためです。代わりに、カウントの値をローカルに格納し、そのローカルを上限としてループします。

于 2013-02-12T14:19:37.580 に答える