编写高质量C#代码(5)

建议14: 正确实现浅拷贝和深拷贝

一、浅拷贝
浅拷贝 将对象中的所有字段复制到新的对象(副本)中。其中,值类型字段的值被复制到副本中后,在副本中的修改不会影响到源对象对应的值。而引用类型的字段被复制到副本中的是引用类型的引用,而不是引用的对象,在副本中对引用类型的字段值做修改会影响到源对象本身。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 浅拷贝和深拷贝
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee mike = new Employee() { IDCode = "NB123", Age = 25, Department = new Department() { Name = "dep1" } };
            Employee rose = mike.Clone() as Employee;
            Console.WriteLine(rose.IDCode);
            Console.WriteLine(rose.Age);
            Console.WriteLine(rose.Department);
            Console.WriteLine("======开始改变源对象mike的值======");
            mike.IDCode = "NB456";
            mike.Age = 60;
            mike.Department.Name = "Dep2";
            Console.WriteLine(rose.IDCode);
            Console.WriteLine(rose.Age);
            Console.WriteLine(rose.Department);
            /*注意到Employee的IDCode属性是string类型。理论上string类型是引用类型,
             * 但是由于该引用类型的特殊性(无论是实现还是语义),Object.MemberwiseClone方法仍旧为其创建了副本。
             * 也就是说,在浅拷贝过程,我们应该将字符串看成是值类型。 Employee的Department属性是一个引用类型,所以,
             * 如果改变了源对象mike中的值,副本rose中的值也会随之一起变动
             */
        }
    }
  
    /// <summary>
    /// 该类实现浅拷贝
    /// </summary>
    class Employee : ICloneable  
    {
        public string IDCode { get; set; }
        public int Age{get;set;}
        public Department Department { get; set; }

        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }
    public class Department
    {
        public string Name { get; set; }
        public override string ToString()
        {
            return this.Name;
        }
    }
}
二、深拷贝
深拷贝 同样,将对象中的所有字段复制到新的对象中。不过,无论是对象的值类型字段,还是引用类型字段,都会被重新创建并赋值,对于副本的修改,不会影响到源对象本身。
Employee的深拷贝有多种实现方法,最简单的方法是手动对字段逐个进行赋值。但这种方法容易出错,也就是说,如果类型的字段发生变化或有增减,那么该拷贝方法也要发生相应的变化,所以,建议使用序列化的形式来进行深拷贝。Employee深拷贝的一个简单实现代码如下所示:
 class Program
    {
        static void Main(string[] args)
        {
            Employee mike = new Employee() { IDCode = "NB123", Age = 25, Department = new Department() { Name = "dep1" } };
            Employee rose = mike.Clone() as Employee;
            Console.WriteLine(rose.IDCode);
            Console.WriteLine(rose.Age);
            Console.WriteLine(rose.Department);
            Console.WriteLine("======开始改变源对象mike的值======");
            mike.IDCode = "NB456";
            mike.Age = 60;
            mike.Department.Name = "Dep2";
            Console.WriteLine(rose.IDCode);
            Console.WriteLine(rose.Age);
            Console.WriteLine(rose.Department);
            /*深拷贝的输出:
             NB123
             25
             dep1
             ======开始改变源对象mike的值======
             NB123
             25
             dep1
             请按任意键继续. . .
             * 可以发现没有改变副本的值
             */            
        }
    }
    /// <summary>
    /// 该类实现深拷贝
    /// </summary>
    [Serializable]
    class Employee : ICloneable
    {
        public string IDCode { get; set; }
        public int Age { get; set; }
        public Department Department { get; set; }

        public object Clone()
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, this);//序列化
                objectStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as Employee;//反序列化
            }
        }
    }
 [Serializable]
    public class Department
    {
        public string Name { get; set; }
        public override string ToString()
        {
            return this.Name;
        }
    }

可以发现,再次更改mike的值已经不会影响副本rose的值了。 由于接口ICloneable只有一个模棱两可的Clone方法,所以,如果要在一个类中同时实现深拷贝和浅拷贝,只能由我们自己实现两个额外的方法,声明为DeepClone和Shallow。Employee的最终版本看起来应该像如下的形式:
  1. [Serializable]  
  2. class Employee : ICloneable  
  3. {  
  4.     public string IDCode { get; set; }  
  5.     public int Age { get; set; }  
  6.     public Department Department { get; set; }  
  7.  
  8.     #region ICloneable 成员  
  9.  
  10.     public object Clone()  
  11.     {  
  12.         return this.MemberwiseClone();  
  13.     }  
  14.  
  15.     #endregion  
  16.  
  17.     public Employee DeepClone()  
  18.     {  
  19.         using (Stream objectStream = new MemoryStream())  
  20.         {  
  21.             IFormatter formatter = new BinaryFormatter();  
  22.             formatter.Serialize(objectStream, this);  
  23.             objectStream.Seek(0, SeekOrigin.Begin);  
  24.             return formatter.Deserialize(objectStream) as Employee;  
  25.         }  
  26.     }  
  27.  
  28.     public Employee ShallowClone()  
  29.     {  
  30.         return Clone() as Employee;  
  31.     }  
三、总结
无论是浅拷贝还是深拷贝,微软都建议用类型继承ICloneable接口的方式明确告诉调用者:该类型可以被拷贝。当然,ICloneable接口只提供了一个声明为Clone的方法,我们可以根据需求在Clone方法内实现浅拷贝或深拷贝


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值