C# 如何正确克隆 List<MyObject>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9622211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make correct clone of the List<MyObject>?
提问by Developer
Possible Duplicate:
How do I clone a generic list in C#?
可能的重复:
如何在 C# 中克隆通用列表?
List<MyObject> a1 = new List<MyObject>();
var new1 = a1;
Now if I change a1then new1is going to be changed as well.
现在如果我改变,a1那么我new1也会改变。
So my question is how to make a clone of a1correctly?
所以我的问题是如何正确制作a1的克隆?
采纳答案by aqwert
This wont Cloneeach item in the list but will create you a new list
这不会Clone是列表中的每个项目,但会为您创建一个新列表
var new1 = new List<MyObject>(a1);
If you want to clone each Item in the list you can implement ICloneableon MyObject
如果您想克隆列表中的每个项目,您可以ICloneable在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 a1into a new list. You just need to decide if you want to have new MyObjects or keep the originals. If you want to clone MyObjectyou will need a way to clone them which typically is done through ICloneable.
编辑:为了使它更清楚一点,两者都将列表中的元素复制a1到新列表中。您只需要决定是要新MyObject的还是保留原件。如果你想克隆,MyObject你需要一种方法来克隆它们,这通常是通过ICloneable.
回答by MAckerman
Or, you could do something like this:
或者,您可以执行以下操作:
public static class CloneClass
{
/// <summary>
/// Clones a object via shallow copy
/// </summary>
/// <typeparam name="T">Object Type to Clone</typeparam>
/// <param name="obj">Object to Clone</param>
/// <returns>New Object reference</returns>
public static T CloneObject<T>(this T obj) where T : class
{
if (obj == null) return null;
System.Reflection.MethodInfo inst = obj.GetType().GetMethod("MemberwiseClone",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (inst != null)
return (T)inst.Invoke(obj, null);
else
return null;
}
}
Then use it like:
然后像这样使用它:
var new1 = CloneClass.CloneObject<List<<MyObject>>(a1);
回答by Jesse
I think the general practice is to avoid using Clonebecause it's not clear if it's a Shallow vs Deep copy of the object.
我认为一般的做法是避免使用Clone,因为不清楚它是对象的浅拷贝还是深拷贝。
More on that here: http://blogs.msdn.com/b/brada/archive/2004/05/03/125427.aspx
更多关于这里:http: //blogs.msdn.com/b/brada/archive/2004/05/03/125427.aspx
A fairly common solution has been to use the BinaryFormatter class to serialize/derialize an object and return the new instance, but with the caveat that the class must be serializable:
一个相当常见的解决方案是使用 BinaryFormatter 类来序列化/反序列化一个对象并返回新实例,但需要注意的是该类必须是可序列化的:
https://stackoverflow.com/a/1213649/1212407
https://stackoverflow.com/a/1213649/1212407
Assuming the above, you could do:
假设以上,你可以这样做:
var clonedList = originaList.DeepClone();

