### 类的深拷贝和浅拷贝
1. 若要深拷贝,当前类和引用的类都需要支持序列化
2. 扩展类的拷贝
3. 代码示例
````C#
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<DataTest> list = new List<DataTest>() { new DataTest() { i=1, str="2131" } };
var list1 = list.Clone() as List<DataTest>;
list[0].i = 2;
list1[0].list[0].ii = 22;
}
}
[Serializable]
public class DataTest:ICloneable
{
public int i = 0;
public string str = "";
public List<DataTest1> list = new List<DataTest1>() { new DataTest1() { ii=2, strr="2313" } };
public List<int> listi = new List<int>() { 1,2,3,4};
public object Clone()
{
//返回浅拷贝
//return MemberwiseClone() as DataTest;
//返回深拷贝
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
return binaryFormatter.Deserialize(memoryStream) as DataTest;
}
}
[Serializable]
public class DataTest1
{
public int ii = 0;
public string strr = "";
}
public static class Ex
{
public static IEnumerable<T> Clone<T>(this IEnumerable<T> listToClone) where T : ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
}
````