问题
I have the following code:
Queue<string> oldQueue = new Queue<string>();
oldQueue.Enqueue("One");
oldQueue.Enqueue("Two");
oldQueue.Enqueue("Three");
Queue newQueue = oldQueue;
string newString = newQueue.Dequeue();
The problem is that once I Dequeue the item from newQueue
, the item is also Dequeued from oldQueue
.
Is there a way to "clone" a queue in a way that removing an item from one queue will keep it's clone queue unchanged?
回答1:
Queue is a reference type, so newQueue and oldQueue holds a pointer to the same object. They are the same ;-)
See this answer about how to do a "deep cloning" using reflection:
Deep Copy using Reflection in an Extension Method for Silverlight?
回答2:
You have to make a deeper copy:
//Queue newQueue = oldQueue;
Queue<string> newQueue = new Queue<string>(oldQueue);
来源:https://stackoverflow.com/questions/16209747/cloning-queue-in-c-sharp