C#中使用DataContractSerializer類實現(xiàn)深拷貝操作示例
一、實現(xiàn)深拷貝方法
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 程序執(zhí)行結果
從結果了解到,s與s1的內容完全一致。
三、真的是深拷貝嗎
為了驗證這點,在代碼Student s1 = DeepCopy.DeepCopyByDCS(s);的后面加入以下代碼:
s.Id = 2; s.Name = "sanwuyueer"; s.Score = new Score() { ChineseScore = 0, MathScore = 0 };
使用這些代碼修改對象s的值后再次輸出對象s1的值,發(fā)現(xiàn)s1的內容并沒有發(fā)生改變,說明s1是一個與s無關的新對象,確實是深拷貝。
四、DataContractSerializer類實現(xiàn)深拷貝的原理
先使用DataContractSerializer類的實例方法WriteObject將對象的完整內容寫入流,再使用實例方法ReadObject讀取流內容并生成反序列化的對象。
相關文章
C# 復制指定節(jié)點的所有子孫節(jié)點到新建的節(jié)點下
這篇文章主要介紹了C# 復制指定節(jié)點的所有子孫節(jié)點到新建的節(jié)點下的相關資料,非常不錯具有一定的參考借鑒價值,需要的朋友可以參考下2016-10-10winform導出dataviewgrid數(shù)據為excel的方法
這篇文章主要介紹了winform導出dataviewgrid數(shù)據為excel的方法,可實現(xiàn)將dataViewGrid視圖中的數(shù)據導出為excel格式的功能,非常具有實用價值,需要的朋友可以參考下2015-01-01C# KeyUp事件中MessageBox的回車(Enter)鍵回調問題解決方案
這篇文章主要介紹了C# KeyUp事件中MessageBox的回車(Enter)鍵回調問題解決方案,需要的朋友可以參考下2014-07-07