/* Use serialization to implement deep copy
* Notes
* 1. Public constructors without parameters must be included
* 2. If a set is included, the set must be of the mandatory type.
* 3. The set must have the same default attribute as the type.
* 4. The set must have the same add method as the type.
* 5. objects to be serialized cannot be referenced cyclically.
*/
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. runtime. serialization. formatters. Binary;
Using system. IO;
Namespace consoleapplication1
{
[Serializable]
Public abstract class animal
{
Public int I;
Public double D;
Public byte B;
Public String [] S;
Public abstract animal clone ();
Public abstract animal createdeepcopy ();
}
[Serializable]
Public class Dog: Animal
{
Public dog (int I, double D, byte B, string S1, string S2)
{
This. I = I;
This. d = D;
This. B = B;
String [] MS = {S1, S2 };
This. S = MS;
}
Public override animal clone ()
{
Return (animal) This. memberwiseclone ();
}
// Implement deep copy
Public override animal createdeepcopy ()
{
Animal animal;
Memorystream = new memorystream ();
Binaryformatter formatter = new binaryformatter ();
Formatter. serialize (memorystream, this );
Memorystream. Position = 0;
// Deserialization
Animal = (animal) formatter. deserialize (memorystream );
Return animal;
}
}
Public class app
{
Public static void main ()
{
Animal a1 = new dog (1, 2, 3, "A", "B ");
System. console. writeline ("Animal A1's members: I = {0} d = {1} B = {2} S1 = {3} S2 = {4}", a1. I, a1.d, a1. B, a1.s [0], a1.s [1]);
Animal A2;
// A2 = a1.clone ();
A2 = a1.createdeepcopy ();
System. console. writeline ("Animal A2's members: I = {0} d = {1} B = {2} S1 = {3} S2 = {4}", a2. I, a2.d, a2. B, a2.s [0], a2.s [1]);
System. Console. Readline ();
System. Console. writeline ("Do a1. I = 9; a1.s [0] = C ");
A1. I = 9; a1.s [0] = "C ";
System. console. writeline ("Animal A1's members: I = {0} d = {1} B = {2} S1 = {3} S2 = {4}", a1. I, a1.d, a1. B, a1.s [0], a1.s [1]);
System. console. writeline ("Animal A2's members: I = {0} d = {1} B = {2} S1 = {3} S2 = {4}", a2. I, a2.d, a2. B, a2.s [0], a2.s [1]);
System. Console. writeline ("Do a2. I = 8; a2.s [1] = D ");
A2. I = 8; a2.s [1] = "D ";
System. console. writeline ("Animal A1's members: I = {0} d = {1} B = {2} S1 = {3} S2 = {4}", a1. I, a1.d, a1. B, a1.s [0], a1.s [1]);
System. console. writeline ("Animal A2's members: I = {0} d = {1} B = {2} S1 = {3} S2 = {4}", a2. I, a2.d, a2. B, a2.s [0], a2.s [1]);
System. Console. Readline ();
}
}
}
Source: http://blog.csdn.net/Open2ye/archive/2006/05/06/710602.aspx