ITPub博客

首页 > Linux操作系统 > Linux操作系统 > c#浅复制与深复制

c#浅复制与深复制

原创 Linux操作系统 作者:wisdomone1 时间:2012-06-08 16:33:23 0 删除 编辑
浅复制
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();
        }
        
    }

}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9240380/viewspace-732313/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
提供针对oracle初学者及进阶的数据库培训,欢迎大家咨询: 微信: wisdomone 微信公众号: lovedb 工作经历: 中国普天 北京科蓝 北京云和恩墨 北京神州新桥

注册时间:2008-04-04

  • 博文量
    2189
  • 访问量
    12690141