【发布时间】:2016-02-01 11:50:33
【问题描述】:
您好,我有一个对象列表 (list1),我想复制此列表,但我希望第二个列表 (list2) 中的对象不链接到第一个列表中的对象。
这就是我的工作
list<Obj> list1 = new list<Obj>{};
// I fill the list1 with objects Obj
// now I want to make a deep copy this is what I do
list<Obj> list2 = new list<Obj>(list1);
// but when I edit an object in list 1 I also edit the object in list2
我希望能够在不编辑 list2 中的对象的情况下编辑 list1 中的对象,我怎样才能得到呢???
感谢您的回答
【问题讨论】:
-
假设您的 Obj 不是值类型,您将不得不遍历您的“list1”并克隆每个单独的对象(并将其添加到 list2)。
-
如果不想实现ICloneable,可以使用这个方法:stackoverflow.com/a/78612/891715
标签: c# list object copy deep-copy