如何使名单,其中正确的克隆;为MyObject>? [英] How to make correct clone of the List<MyObject>?

查看:160
本文介绍了如何使名单,其中正确的克隆;为MyObject>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  我如何克隆一个泛型列表在C#?

 名单,其中,为MyObject> A1 =新的名单,其中,为MyObject>();

VAR名new1 = A1;
 

现在,如果我更改 A1 然后名new1 将要随之改变。

所以我的问题是如何的做的克隆 A1 是否正确?

解决方案

这不会克隆列表中的每个项目,但会造成你一个新的列表

(A1);

  VAR名new1 =新的名单,其中,为MyObject>
 

如果你想克隆列表中的每个项目可以实施 ICloneable 为MyObject

  VAR名new1 =新的名单,其中,为MyObject>(a1.Select(X => x.Clone()));
 

编辑: 为了使它更清楚一点双方将从列表 A1 复制元素融入一个新的列表。你只需要决定,如果你想有新的为MyObject s或保存原件。如果要克隆为MyObject ,你需要一种方法来克隆它们通常是通过 ICloneable 完成的。

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

List<MyObject> a1 = new List<MyObject>();

var new1 = a1;

Now if I change a1 then new1 is going to be changed as well.

So my question is how to make a clone of a1 correctly?

解决方案

This wont Clone each item in the list but will create you a new list

var new1 = new List<MyObject>(a1);

If you want to clone each Item in the list you can implement ICloneable on MyObject

var new1 = new List<MyObject>(a1.Select(x => x.Clone()));

EDIT: To make it a bit clearer both will copy the elements from list a1 into a new list. You just need to decide if you want to have new MyObjects or keep the originals. If you want to clone MyObject you will need a way to clone them which typically is done through ICloneable.

这篇关于如何使名单,其中正确的克隆;为MyObject&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆