0

我正在尝试为我的客户制作订单队列。但是最后一个添加的值替换了队列中的所有值。

调试代码我看到,当一个值入队时,它会覆盖队列中的所有其他值。

class Program
{

    static void Main(string[] args)
    {
        Console.WriteLine("Starting...");
        byte[] dataInit = new byte[] { 0x00 };
        Client clientTest = new Client();


        for (int i = 0; i <= 5; i++)
        {
            dataInit[0]++;
            Console.WriteLine("Adding Order -  i = {0}; Order: {1}.", i, BitConverter.ToString(dataInit));
            clientTest.AddOrder(dataInit);
            Console.WriteLine("Peeking Order - i = {0}; Order: {1}", i, BitConverter.ToString(clientTest.PeekOrder()));
        }

        for (int i = 0; i <= 5; i++)
        {
            Console.WriteLine("Removing order - i = {0}; Order: {1}.", i, BitConverter.ToString(clientTest.RemoveOrder()));
        }

        Console.WriteLine("Press Any Key...");
        Console.Read();

    }

    class ClientOrder
    {
        public byte[] Order;


        public ClientOrder(byte[] data)
        {
            Order = data;
        }


    }

    class Client
    {
        public Queue<ClientOrder> ClientOrders = new Queue<ClientOrder>();

        public void AddOrder(byte[] orderToAdd)
        {
            ClientOrders.Enqueue(new ClientOrder(orderToAdd));
        }

        public byte[] RemoveOrder()
        {

            ClientOrder toReturn = ClientOrders.Dequeue();
            return toReturn.Order;
        }

        public byte[] PeekOrder()
        {
            ClientOrder toReturn = ClientOrders.Peek();
            return toReturn.Order;
        }
    }
}

我预计队列是有序的 [0-6]。但实际输出是 {06,06,06,06,06,06} (最后添加的值)。

4

1 回答 1

2

您实际上共享相同的引用byte[],然后每次Enqueue您实际替换队列中的所有元素,因为它们都引用相同的数组。创建时应制作副本ClientOrder。简单的方法是使用Linq,但也有其他的可能性

public ClientOrder(byte[] data)
{
    Order = data.ToArray();
}

或杰夫所说的其他方式

于 2019-02-14T20:42:31.510 回答