一、基本概念
1、深拷贝
深拷贝要求将要clone的对象的引用类型成员对象也拷贝到新对象中,而不是拷贝这些对象的引用(浅拷贝)。
2、序列化
将对象或对象图形转换成线性字节序列,以存储或传输到另一个位置的过程。
3、反序列化
接受存储的信息并利用它重新创建对象的过程。
二、案例实现
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Reflection;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Runtime.Serialization;
- namespace DeepCopy
- {
- static class Program
- {
- [Serializable]
- public class CPerson : ICloneable
- {
- public int Age { get; set; }
- public string Address { get; set; }
- public Name Name { get; set; }
-
- public object Clone()
- {
- using (MemoryStream ms = new MemoryStream(1000))
- {
- object cloneO;
- BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
- /* 序列化 */
- bf.Serialize(ms, this);
- ms.Seek(0, SeekOrigin.Begin);
-
- /* 反序列化 */
- cloneO = bf.Deserialize(ms);
- ms.Close();
- return cloneO;
- }
- }
- }
-
- [Serializable]
- public class Name
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
-
- public Name(string firstName, string lastName)
- {
- FirstName = firstName;
- LastName = lastName;
- }
- }
-
- static void Main(string[] args)
- {
- CPerson cp1 = new CPerson();
- cp1.Age = 1;
- cp1.Address = "Road 1";
- cp1.Name = new Name("Lebron1", "James1");
-
- CPerson cp2 = (CPerson)cp1.Clone();
- Console.WriteLine("cp1.Age={0},cp1.Address={1},cp1.Name={2} {3}", cp1.Age, cp1.Address, cp1.Name.FirstName, cp1.Name.LastName);
- Console.WriteLine("cp2.Age={0},cp2.Address={1},cp2.Name={2} {3}", cp2.Age, cp2.Address, cp2.Name.FirstName, cp2.Name.LastName);
- Console.WriteLine("-------------------------------------------------");
- cp2.Name = new Name("Kobe1", "Brynt");
- Console.WriteLine("cp2.Age={0},cp2.Address={1},cp2.Name={2} {3}", cp2.Age, cp2.Address, cp2.Name.FirstName, cp2.Name.LastName);
-
- Console.ReadKey();
- }
- }
- }
三、注意事项
通过序列化和反序列化实现深拷贝,其和其字段类型必须标记为可序列化类型,
既添加特性
(Attribute)[Serializable]
参考博客: