我有一个名为“SmallClass”的 C# 类。
我有一个包含“SmallClass”类型对象的现有列表 myList
我想要列表“myList”的深层克隆。即深度克隆包含列表,深度克隆列表中包含的对象。
我该怎么做。
public class SmallClass: ICloneable {
public string str1;
public string str2;
public string str3;
public SmallClass Clone() //This just deep clones 1 object of type "SmallClass"
{
MemoryStream m = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
b.Serialize(m, this);
m.Position = 0;
return (SRO)b.Deserialize(m);
}
public override equals(Object a)
{
return Object.Equals(this.str1 && a.str1);
}
}
public class AnotherClass
{
SomeCode();
List<SmallClass> myList = new List<SmallList>(); //myList is initialized.
// NOW I want to deep clone myList. deep Clone the containing list and deep clone the objects contained in the list.
List<SmallClass> newList = new List<SmallClass>();
foreach(var item in myList)
{
newList.Add((SmallClass)item.Clone());
}
Run Code Online (Sandbox Code Playgroud)
}
首先,您可以定义一个用于深度克隆任何对象(根)的实用方法:
public static T DeepClone<T>(T obj)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Position = 0;
return (T)formatter.Deserialize(stream);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想深度克隆myList,你需要做的就是将它作为参数传递给上面的方法:
List<SmallClass> myListClone = DeepClone(myList);
Run Code Online (Sandbox Code Playgroud)
您需要注意的最重要的考虑因素是您的所有类都必须标记为可序列化,通常通过[SerializableAttribute].
[SerializableAttribute]
public class SmallClass
{
// …
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5763 次 |
| 最近记录: |