深拷贝于浅拷贝

为对象创建副本的技术成为拷贝(也叫克隆)。我们将拷贝分为浅拷贝和深拷贝。

1.浅拷贝:将对象的所有字段赋值到新的对象(副本)中。其中,值类型字段的值北复制到副本中后,在副本中的修改不会影响到源对象对应的值。而应用类型的字段被复制到副本中的是引用对象,在副本中对引用类型的字段值做修改会影响到源对象本身。

2.沈拷贝:同样,将对象中的所有字段复制到新的对象中。不过,无论是对象的值类型字段,还是引用类型字段,都会被重新创建病赋值,对于副本的修改,不会影响到源对象本身。

3.例子:

class Person : ICloneable
    {
        public string name;
        public int age;
        public Department department;

        //浅拷贝
        public Person ShallowClone()
        {
            return ShallowClone() as Person;
        }

        //深拷贝
        public Person DeepClone()
        {
            using(Stream objStream = new MemoryStream()){
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objStream, this);
                objStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objStream) as Person;
            }
        }

        public override string ToString()
        {
            return "姓名:" + this.name + ",年龄:" + this.age.ToString() + ",部门:" + this.department.name;
        }



        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }

 

posted @ 2016-08-09 10:39  曹国栋  阅读(135)  评论(0编辑  收藏  举报