1

谁能帮我理解为什么for loops下面两个的输出会产生不同的输出?

在我看来它们是相同的,但是原始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是 9,i0
第二次迭代:requestQueue.Count是 8,i1.
第三次迭代: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-loopQueue.Dequeue删除了第一个项目,这也减少了Count属性。这就是它“中途”停止的原因。

循环变量i仍在增加而Count正在减少。

于 2013-02-12T14:17:33.060 回答
1

因为每次调用 requestQueue.Dequeue() 时都会更改 requestQueue 中的项目数量。而是将 count 的值存储在本地并以该本地作为上限进行循环。

于 2013-02-12T14:19:37.580 回答