1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Runtime.Serialization; 6 using System.Runtime.Serialization.Formatters.Binary; 7 using System.Text; 8 namespace DeSerializable 9 { 10 public class Dog : Exception 11 { 12 public readonly string Name = "David Lee"; 13 public static Dog Instrance = new Dog(); 14 private Dog() 15 { 16 } 17 public override string ToString() 18 { 19 return string.Format("{0}小狗汪汪叫!", Name); 20 } 21 } 22 class Program 23 { 24 static void Main(string[] args) 25 { 26 Dog dog = DeepCopyDog(); 27 Dog originalDog = Dog.Instrance; 28 if (ReferenceEquals(dog,originalDog)) 29 { 30 Console.WriteLine("深拷贝失败"); 31 } 32 else 33 { 34 Console.WriteLine("拷贝成功,恭喜"); 35 } 36 Console.ReadLine(); 37 } 38 public static Dog DeepCopyDog() 39 { 40 Dog dog = Dog.Instrance; 41 using (MemoryStream ms = new MemoryStream()) 42 { 43 BinaryFormatter bfFormatter = new BinaryFormatter(); 44 bfFormatter.Serialize(ms, dog); 45 ms.Position = ms.Seek(0, SeekOrigin.Begin); 46 return bfFormatter.Deserialize(ms) as Dog; 47 } 48 } 49 } 50 }
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Runtime.Serialization; 6 using System.Runtime.Serialization.Formatters.Binary; 7 using System.Text; 8 namespace DeSerializable 9 { 10 public class Dog : Exception 11 { 12 public readonly string Name = "David Lee"; 13 public static Dog Instrance = new Dog(); 14 private Dog() 15 { 16 } 17 public override string ToString() 18 { 19 return string.Format("{0}小狗汪汪叫!", Name); 20 } 21 } 22 class Program 23 { 24 static void Main(string[] args) 25 { 26 Dog dog = DeepCopyDog(); 27 Dog originalDog = Dog.Instrance; 28 if (ReferenceEquals(dog,originalDog)) 29 { 30 Console.WriteLine("深拷贝失败"); 31 } 32 else 33 { 34 Console.WriteLine("拷贝成功,恭喜"); 35 } 36 Console.ReadLine(); 37 } 38 public static Dog DeepCopyDog() 39 { 40 Dog dog = Dog.Instrance; 41 using (MemoryStream ms = new MemoryStream()) 42 { 43 BinaryFormatter bfFormatter = new BinaryFormatter(); 44 bfFormatter.Serialize(ms, dog); 45 ms.Position = ms.Seek(0, SeekOrigin.Begin); 46 return bfFormatter.Deserialize(ms) as Dog; 47 } 48 } 49 } 50 }
[Serializable] public class Dog : Exception { public readonly string Name = "David Lee"; public static Dog Instrance = new Dog(); private Dog() { } protected Dog(SerializationInfo information, StreamingContext context) { } public override string ToString() { return string.Format("{0}小狗汪汪叫!", Name); } }
Serializable特性还是要添加的,另外还需要加上一个构造,才能保证序列化成功。