16.深度复制和浅度复制

1.浅度复制

使用System.Object类的MemberwiseClone()方法可以进行浅度复制,该方法的作用通过创建一个当前类的新实例,并简单把其成员变量赋值给新实例的成员变量以达到复制当前对象的效果。这样复制的结果是新对象和原对象不是同一对象,但是其引用类型的成员和原对象是同一个引用。

    class Cloner
    {
        public Content MyContent = new Content();
        public Cloner(int newVal)
        {
           MyContent.Val = newVal;
        }

        public Cloner GetCopy()
        {
            return (Cloner)this.MemberwiseClone();
        }
    }

    class Content
    {
        public int Val;
    }

    class Program
    {

        static void Main(string[] args)
        {
            Cloner c1 = new Cloner(5);
            Cloner c2 = c1.GetCopy();
            Console.WriteLine(c1.MyContent.Val);//5
            c2.MyContent.Val = 2;
            Console.WriteLine(c1.MyContent.Val);//2
            Console.ReadLine();
        }
    }

2.深度复制

要完完整整的复制一个对象,需要用到深度复制。.net提供了进行深度复制的标准方法,我们只需要实现ICloneable接口的Clone()方法即可。

    class Cloner:ICloneable
    {
        public Content MyContent = new Content();
        public Cloner(int newVal)
        {
           MyContent.Val = newVal;
        }

        public object Clone()
        {
            Cloner c = new Cloner(MyContent.Val);
            return c;
        }
    }

    class Content
    {
        public int Val;
    }

    class Program
    {

        static void Main(string[] args)
        {
            Cloner c1 = new Cloner(5);
            Cloner c2 = (Cloner)c1.Clone();
            Console.WriteLine(c1.MyContent.Val);//5
            c2.MyContent.Val = 2;
            Console.WriteLine(c1.MyContent.Val);//5
            Console.ReadLine();
        }
    }

以上深度复制是比较简单的,在比较复杂的对象系统中,调用Clone()是一个递归过程。假如上面的例子中的MyContent成员也需要深度复制,需要用到下面代码

    class Cloner:ICloneable
    {
        public Content MyContent = new Content();
        public Cloner(int newVal)
        {
           MyContent.Val = newVal;
        }

        public Cloner()
        { 
            
        }

        public object Clone()
        {
            Cloner c = new Cloner(MyContent.Val);
            c.MyContent = (Content)MyContent.Clone();
            return c;
        }
    }

    class Content:ICloneable
    {
        public int Val;

        public object Clone()
        {
            Content c = new Content();
            c.Val = Val;
            return c;
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            Cloner c1 = new Cloner(5);
            Cloner c2 = (Cloner)c1.Clone();
            Console.WriteLine(c1.MyContent.Val);//5
            c2.MyContent.Val = 2;
            Console.WriteLine(c1.MyContent.Val);//5
            Console.ReadLine();
        }
    }
原文地址:https://www.cnblogs.com/lidaying5/p/10565324.html