排队字节数组有问题

时间:2015-08-11 12:27:15

标签: c# queue

最简单的例子。我试图像这样创建一个字节数组的队列:

        Queue<Byte[]> q = new Queue<Byte[]>();
        Byte[] block = new Byte[1];
        block[0] = 1;
        q.Enqueue(block);
        block[0] = 2;
        q.Enqueue(block);
        block[0] = 3;
        q.Enqueue(block);
        byte[] block1 = q.Dequeue();
        Console.WriteLine(block1[0]);
        block1 = q.Dequeue();
        Console.WriteLine(block1[0]);
        block1 = q.Dequeue();
        Console.WriteLine(block1[0]);

但事实上,我所有的三个街区都是&#34; 3&#34;但是预计&#34; 1&#34; &#34; 2&#34; &#34; 3&#34 ;.我有什么想法我做错了吗?

1 个答案:

答案 0 :(得分:3)

您需要每次创建一个新数组,否则您只需更改同一个数组并将其多个引用添加到Queue

Queue<Byte[]> q = new Queue<Byte[]>();
Byte[] block = new Byte[1];
block[0] = 1;
q.Enqueue(block);

// Create a new array
block = new Byte[1];
block[0] = 2;
q.Enqueue(block);

// Create a new array
block = new Byte[1];
block[0] = 3;
q.Enqueue(block);
byte[] block1 = q.Dequeue();
Console.WriteLine(block1[0]);
block1 = q.Dequeue();
Console.WriteLine(block1[0]);
block1 = q.Dequeue();
Console.WriteLine(block1[0]);