我有一个名为“SmallClass”的 C# 类。
我有一个现有列表 myList 包含“SmallClass”类型的对象
我想要列表“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());
}
}