C#整理——深浅度复制

一:浅度复制(新对象的引用成员指向源对象中相同引用成员的对象,即另个不同对象的相同类型的引用指向同一个对象):

如:

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

namespace ConsoleApplication13
{
    public class Content
    {
        public int Val2;
    }

    public class Cloner
    {
        public int Val;
        public Content Mycontent = new Content();//这是引用类型的字段,可以进行浅复制;
        public Cloner(int newVal)
       {
           Mycontent.Val2 = newVal;
           Val=newVal;  //Val不是引用类型而是值类型,所以不能进行浅复制,就算进行了也无效;
       }
        public object GetCopy()
        {
            return MemberwiseClone();
        }
    }
    class Tester
    {
        static void Main(string[] args)
        {
            Cloner source = new Cloner(5);
            Cloner target = (Cloner)source.GetCopy();
            Console.WriteLine("{0},{1}",target.Val,target.Mycontent.Val2);
            source.Mycontent.Val2 = 8;
            Console.WriteLine("{0},{1}", target.Val, target.Mycontent.Val2);
            Console.ReadKey();
        }
    }

}

结果:5,5

        5,8

二:深复制(进行深复制的类要实习ICloneable接口)(理解:同一个类的不同对象的相同类型的引用之间只是完成了由一方给另一方赋值,这两个引用并没有指向同一对象)

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

namespace ConsoleApplication13
{
    public class Content
    {
        public int Val2;
    }

    public class Cloner:ICloneable
    {
        public int Val;
        public Content Mycontent = new Content();
        public Cloner(int newVal)
       {
           Mycontent.Val2 = newVal;
           Val=newVal;  
       }
        public object Clone()
        {
            Cloner clonedCloner = new Cloner(Mycontent.Val2);
             return clonedCloner;
        }
    }
    class Tester
    {
        static void Main(string[] args)
        {
            Cloner source = new Cloner(5);
            Cloner target = (Cloner)source.Clone();
            Console.WriteLine("{0},{1}",target.Val,target.Mycontent.Val2);
            source.Mycontent.Val2 = 8;
            Console.WriteLine("{0},{1}", target.Val, target.Mycontent.Val2);
            Console.ReadKey();
        }
    }

}

结果:5,5

       5,5

 

posted @ 2013-07-22 11:03  liaojinpiao  阅读(221)  评论(0编辑  收藏  举报