C#中應用DataContractSerializer類完成深拷貝操作示例。本站提示廣大學習愛好者:(C#中應用DataContractSerializer類完成深拷貝操作示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中應用DataContractSerializer類完成深拷貝操作示例正文
1、完成深拷貝辦法
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、測試深拷貝辦法
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的內容完整分歧。
3、真的是深拷貝嗎
為了驗證這點,在代碼Student s1 = DeepCopy.DeepCopyByDCS(s);的前面參加以下代碼:
s.Id = 2; s.Name = "sanwuyueer"; s.Score = new Score() { ChineseScore = 0, MathScore = 0 };
應用這些代碼修正對象s的值後再次輸入對象s1的值,發明s1的內容並沒有產生轉變,解釋s1是一個與s有關的新對象,確切是深拷貝。
4、DataContractSerializer類完成深拷貝的道理
先應用DataContractSerializer類的實例辦法WriteObject將對象的完全內容寫入流,再應用實例辦法ReadObject讀取流內容並生成反序列化的對象。