1 /// <summary>
2 /// 對象的深度拷貝(序列化的方式)
3 /// </summary>
4 public static class MyDeepCopy
5 {
6
7 /// <summary>
8 /// xml序列化的方式實現深拷貝
9 /// </summary>
10 /// <typeparam name="T"></typeparam>
11 /// <param name="t"></param>
12 /// <returns></returns>
13 public static T XmlDeepCopy<T>(T t)
14 {
15 //創建Xml序列化對象
16 XmlSerializer xml = new XmlSerializer(typeof(T));
17 using (MemoryStream ms = new MemoryStream())//創建內存流
18 {
19 //將對象序列化到內存中
20 xml.Serialize(ms, t);
21 ms.Position = default;//將內存流的位置設為0
22 return (T)xml.Deserialize(ms);//繼續反序列化
23 }
24 }
25
26 /// <summary>
27 /// 二進制序列化的方式進行深拷貝
28 /// 確保需要拷貝的類里的所有成員已經標記為 [Serializable] 如果沒有加該特性特報錯
29 /// </summary>
30 /// <typeparam name="T"></typeparam>
31 /// <param name="t"></param>
32 /// <returns></returns>
33 public static T BinaryDeepCopy<T>(T t)
34 {
35 //創建二進制序列化對象
36 BinaryFormatter bf = new BinaryFormatter();
37 using (MemoryStream ms = new MemoryStream())//創建內存流
38 {
39 //將對象序列化到內存中
40 bf.Serialize(ms, t);
41 ms.Position = default;//將內存流的位置設為0
42 return (T)bf.Deserialize(ms);//繼續反序列化
43 }
44 }
45 }