Deep copy with serialization and deserialization (C#)

Class:

Class
1 [Serializable]
2 class SerializeDemo
3 {
4     public String Name;
5     public Int32 Score;
6     [NonSerialized]
7     public String Grade;
8 }

DeepClone<T>:

扩展方法
 1 static class ExtObject
 2 {
 3     public static T DeepClone<T>(this T objectToCopy) where T:class
 4     {
 5         using (MemoryStream stream = new MemoryStream())
 6         {
 7             BinaryFormatter binaryFormatter = new BinaryFormatter();
 8              binaryFormatter.Serialize(stream, objectToCopy);
 9              stream.Seek(0, SeekOrigin.Begin);
10               return (T)binaryFormatter.Deserialize(stream);
11          }
12     }
13 }

Test:

测试
 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             SerializeDemo demo = new SerializeDemo()
 6             {
 7                 Name = "Lei",
 8                 Grade = "Two",
 9                 Score = 100
10             };
11 
12             Console.WriteLine("Shallow Copy:");
13             SerializeDemo shallowCopy = demo;
14             Console.WriteLine(Object.Equals(demo, shallowCopy));
15             Console.WriteLine(shallowCopy.Name);
16             Console.WriteLine(shallowCopy.Score);
17             Console.WriteLine(shallowCopy.Grade);
18             
19             Console.WriteLine("Deep Copy:");
20             SerializeDemo deepCopy = demo.DeepClone<SerializeDemo>();
21             Console.WriteLine(Object.Equals(demo, deepCopy));
22             Console.WriteLine(deepCopy.Name);
23             Console.WriteLine(deepCopy.Score);
24             Console.WriteLine(deepCopy.Grade);
25 
26             Console.ReadLine();
27         }
28     }

Result:

Reference:

【1】http://softwarebydefault.com/2013/02/10/deep-copy-generics/

posted @ 2013-04-26 21:42  BlueMountain_79  阅读(802)  评论(1编辑  收藏  举报