在 class 中创建队列的正确方法是什么?
What is the proper way to make a queue inside a class?
我正在尝试为我的客户制作一个订单队列。
但是最后添加的值替换了队列中的所有值。
调试代码时我发现当一个值入队时它会覆盖队列中的所有其他值。
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}(最后添加的值)。
您实际上共享了对 byte[]
的相同引用,然后对于每个 Enqueue
您实际上替换了队列中的所有元素,因为它们都引用了同一个数组。创建 ClientOrder
时应复制一份。简单的方法是使用 Linq
,但也有其他 .
public ClientOrder(byte[] data)
{
Order = data.ToArray();
}
或所说的其他方式
我正在尝试为我的客户制作一个订单队列。 但是最后添加的值替换了队列中的所有值。
调试代码时我发现当一个值入队时它会覆盖队列中的所有其他值。
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}(最后添加的值)。
您实际上共享了对 byte[]
的相同引用,然后对于每个 Enqueue
您实际上替换了队列中的所有元素,因为它们都引用了同一个数组。创建 ClientOrder
时应复制一份。简单的方法是使用 Linq
,但也有其他
public ClientOrder(byte[] data)
{
Order = data.ToArray();
}
或