cloning a list in C# [duplicate]

非 Y 不嫁゛ 提交于 2019-12-08 08:42:52

问题


Possible Duplicate:
How do I clone a generic list in C#?

hey i have been trying to clone a list and so far i found the function addRange but i am pretty sure it does not clone the objects inside the list but doing a shallow copy of the list i would like to know how to clone the list thanks in advance.


回答1:


To clone a list, each individual item has to be cloned. Provided a useful implementation of Clone() for the item class exists, this is a one-liner using LINQ:

List<MyType> lstCloned = lstOriginal.Select(i => i.Clone()).ToList();



回答2:


AddRange, and more generally all operations on objects contained in list only clones references to these objects. To clone objects themselves, you should handle the copy at the object level itself.

What do you mean by "clone the list" ? Clone the objects ? You can implement it explicitly on each objects (by realizing ICloneable interface for example), or make a general implementation using Reflection.

Look for "ICloneable", "deep cloning" or "deep copy" to learn more on the different ways to get the expected result.




回答3:


You will need to parse the list and create a new object for each item then the new item add it to a new list.



来源:https://stackoverflow.com/questions/4119347/cloning-a-list-in-c-sharp

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