C#中使用DataContractSerializer类实现深拷贝操作示例
一、实现深拷贝方法
using System.IO; using System.Runtime.Serialization; namespace DeepCopyExp { class DeepCopy { public static T DeepCopyByDCS<T>(T obj) { T newObject; using (MemoryStream memoryStream = new MemoryStream()) { DataContractSerializer dcs = new DataContractSerializer(obj.GetType()); dcs.WriteObject(memoryStream, obj); memoryStream.Seek(0, SeekOrigin.Begin); newObject = (T)dcs.ReadObject(memoryStream); } return newObject; } } }
二、测试深拷贝方法
2.1 书写测试代码
using System; namespace DeepCopyExp { class Program { static void Main(string[] args) { Student s = new Student() { Id = 1, Name = "三五月儿", Score = new Score() { ChineseScore =100, MathScore=100} }; Student s1 = DeepCopy.DeepCopyByDCS(s); Console.WriteLine("Id = {0}, Name = {1}, Score.ChineseScore = {2}, Score.MathScore = {3}", s1.Id, s1.Name, s1.Score.ChineseScore, s1.Score.MathScore); } } public class Score { public int ChineseScore { get; set; } public int MathScore { get; set; } } public class Student { public int Id { get; set; } public string Name { get; set; } public Score Score { get; set; } } }
代码中先实例化Student类得到对象s,再使用本文给出的拷贝方法将其拷贝至对象s1并输出s1的内容,s1的内容是不是和s的内容完全一致?
2.2 运行测试代码得到下图所示结果
图1 程序执行结果
从结果了解到,s与s1的内容完全一致。
三、真的是深拷贝吗
为了验证这点,在代码Student s1 = DeepCopy.DeepCopyByDCS(s);的后面加入以下代码:
s.Id = 2; s.Name = "sanwuyueer"; s.Score = new Score() { ChineseScore = 0, MathScore = 0 };
使用这些代码修改对象s的值后再次输出对象s1的值,发现s1的内容并没有发生改变,说明s1是一个与s无关的新对象,确实是深拷贝。
四、DataContractSerializer类实现深拷贝的原理
先使用DataContractSerializer类的实例方法WriteObject将对象的完整内容写入流,再使用实例方法ReadObject读取流内容并生成反序列化的对象。
赞 (0)