[导入]用序列化实现 深copy

/*用序列化实现 深copy
*注意事项
*1.必须带有不带参数的公共构造函数
*2.如果包含集合,那么集合必须是强制类型类型
*3.集合必须有与类型一致的默认属性
*4.集合必须有与类型一致的Add方法
*5.需要序列化的对象不能循环引用
*/
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();
        }
        //实现深拷贝

        public override Animal CreateDeepCopy()
        {
            Animal animal;
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, this);
            memoryStream.Position = 0;
            //反序列化
            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();
        }
    }
}


文章来源: http://blog.csdn.net/Open2ye/archive/2006/05/06/710602.aspx

你可能感兴趣的:(copy)