Ejemplo n.º 1
0
        //浅复制 浅复制也是在副本中重新创建的成员,对应到内存的栈上,分配新的内存空间,引用类型则因为浅复制的时候,对象和对象副本共用同一个引用对象
        //public object Clone()
        //{
        //    return this.MemberwiseClone();
        //}

        // 深复制 不管是值类型的成员还是引用类型的成员,这样的对象和对象副本,对任何一个成员属性的修改,都不会影响到改变对象的
        public object Clone()
        {
            Cup     cup      = (Cup)this.MemberwiseClone();
            Factory factory1 = new Factory();

            factory1.FactoryName = cup.Factory.FactoryName;
            cup.Factory          = factory1;

            return(cup);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Cup cup = new Cup();

            cup.Height = 2;
            Cup cup1 = (Cup)cup.Clone();

            cup1.Height = 1;
            cup1.Factory.FactoryName = "AAA";
            Console.WriteLine(cup.Height == cup1.Height);
            Console.WriteLine(cup.Factory == cup1.Factory);


            //颜色

            IColorDemo color = new RedColor();

            color.Red = 255;

            IColorDemo color1 = color.Clone();

            color1.Blue = 255;
            Console.WriteLine(color.Blue == color1.Blue);

            IColorDemo2 color2 = new RedColor2();

            color.Red = 255;

            IColorDemo2 color3 = color2.Clone();

            color2.Blue = 252;
            Console.WriteLine(color2.Blue == color3.Blue);


            Console.ReadKey();
        }