Cloning queue in c#

倖福魔咒の 提交于 2020-01-04 09:55:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!