c#浅复制与深复制

浅复制
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{


    class light : ICloneable
    {
        public int[] v ={ 1, 2, 3 };
        public object clone()
        {
            return this.MemberwiseClone();
        }


        public void display()
        {
            foreach (int i in v)
            {
                Console.WriteLine(i);

            }
        }


        #region ICloneable 成员

        public object Clone()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        #endregion
    }
   
    //客户端
    class Program
    {
       
        static void Main(string[] args)
        {
            light l1 = new light();
            light l1copy = (light)l1.clone();
            l1.v[0] = 8;
            l1copy.display();
            Console.ReadKey();
        }
        
    }


}


深复制




using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{


    public class light : ICloneable
    {
        public int[] v ={ 1, 2, 3 };

        //默认构造函数
        public light()
        {
        }

        //用于深复制与的私有构造函数
        private light(int[] v)
        {
            this.v =(int[])v.Clone();
        }

        public void display()
        {
            foreach (int i in v)
            {
                Console.WriteLine(i);

            }
        }


        #region ICloneable 成员

        public object Clone()
        {
            return new light(this.v);//此调用了上述的私有构造函数

            //throw new Exception("The method or operation is not implemented.");
        }

        #endregion
    }
   
    //客户端
    class Program
    {
       
        static void Main(string[] args)
        {
            light l1 = new light();//先产生原型对象

            light l1copy = (light)l1.Clone();然后通过上述原型对象的clone方法会去调用私有构造函数进而复制l1为另一个新的对象
            l1.v[0] = 8;
            l1copy.display();
            Console.ReadKey();
        }
        
    }

}

请使用浏览器的分享功能分享到微信等