在班级内排队的正确方法是什么?

时间:2019-02-14 20:30:50

标签: c# queue enqueue

我正在尝试为我的客户安排订单队列。 但是最后添加的值将替换队列中的所有值。

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

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}(最后添加的值)。

1 个答案:

答案 0 :(得分:2)

您实际上共享了对byte[]的相同引用,然后实际上每个Enqueue都替换了队列中的所有元素,因为它们都引用同一数组。创建ClientOrder时应复制一份。简单的方法是使用Linq,但还有其他possibilities

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

Jeff所说的其他方式