C#对象的浅拷贝、序列化深拷贝

来源:互联网 发布:谭铁牛 人工智能 编辑:程序博客网 时间:2024/06/06 01:41
using System;using System.Collections.Generic;//using System.Linq;//using System.Text;//using System.Threading.Tasks;using System.IO;using System.Runtime.Serialization.Formatters.Binary;/// <summary>/// C# 的浅拷贝,序列化深拷贝。/// </summary>namespace DesignPattern.Common.Copy{    public class Client    {        /// <summary>        /// 测试浅拷贝        /// </summary>        public static void Test_ShallowCopy()        {            Console.WriteLine("----浅拷贝");            Employee employee = new Employee();            employee.employeeId = 10;            employee.employeeName = "李四";            Department department = new Department();            department.departmentId = 123;            department.departmentName = "软件部";            employee.department = department;            Console.WriteLine("--拷贝之前");            Console.WriteLine("原来数据:{0}", employee.ToString());            /// 调用浅拷贝的函数            Employee clone = (Employee)employee.ShallowClone();            clone.employeeName = "胡汉三";            clone.department.departmentName = "测试部";            clone.department.departmentId = 456;            Console.WriteLine("--拷贝之后");            Console.WriteLine("原来数据:{0}", employee.ToString());            Console.WriteLine("拷贝数据:{0}", clone.ToString());        }        /// <summary>        /// 测试序列化深拷贝_1        /// </summary>        public static void Test_DeepCopy()        {            Console.WriteLine("----深拷贝");            Employee employee = new Employee();            employee.employeeId = 10;            employee.employeeName = "李四";            Department department = new Department();            department.departmentId = 123;            department.departmentName = "软件部";            employee.department = department;            Console.WriteLine("--拷贝之前");            Console.WriteLine("原来数据:{0}", employee.ToString());            /// ------- 这里重写了对象的深拷贝的方法。            Employee clone = (Employee)employee.Clone();            clone.employeeName = "胡汉三";            clone.department.departmentName = "测试部";            clone.department.departmentId = 456;            Console.WriteLine("--拷贝之后");            Console.WriteLine("原来数据:{0}", employee.ToString());            Console.WriteLine("拷贝数据:{0}", clone.ToString());        }        /// <summary>        /// 测试序列化深拷贝_2        /// </summary>        public static void Test_DeepCopy_2()        {            List<Employee> employees = new List<Employee>();            for (int i = 0, count = 2; i < count; ++i)            {                Employee employee = new Employee();                employee.employeeId = i;                employee.employeeName = "李四";                Department department = new Department();                department.departmentId = 123;                department.departmentName = "软件部";                employee.department = department;                employees.Add(employee);            }            Console.WriteLine("--拷贝之前--输出 原始数据");            for (int i = 0, count = employees.Count; i < count; ++i)            {                Employee employee = employees[i];                Console.WriteLine(employee.ToString());            }            /// 序列化拷贝            List<Employee> employees_2 = ObjectExtension.CopyObject<List<Employee>>(employees);            //List<Employee> employees_2 = new List<Employee>(employees);            for (int i = 0, count = employees_2.Count; i < count; ++i)            {                Employee employee = employees_2[i];                employee.employeeId = i + 100;                employee.department.departmentId += 1000;            }            Console.WriteLine("--拷贝之后--输出 拷贝数据");            for (int i = 0, count = employees_2.Count; i < count; ++i)            {                Employee employee = employees_2[i];                Console.WriteLine(employee.ToString());            }            Console.WriteLine("--拷贝之后--输出 原始数据");            for (int i = 0, count = employees.Count; i < count; ++i)            {                Employee employee = employees[i];                Console.WriteLine(employee.ToString());            }        }    }    #region 浅拷贝,序列化深拷贝    [Serializable]    public class Department    {        public int departmentId { get; set; }        public string departmentName { get; set; }        public override string ToString()        {            return string.Format("GetType() = {0},departmentId = {1},departmentName = {2}", this.GetType().Name, departmentId, departmentName);        }    }    [Serializable]    public class Employee : ICloneable    {        public int employeeId { get; set; }        public string employeeName { get; set; }        public Department department { get; set; }        /// <summary>        /// 浅拷贝        /// </summary>        /// <returns></returns>        public object ShallowClone()        {            object obj = this.MemberwiseClone();            return obj;        }        /// <summary>        /// 深拷贝        /// </summary>        /// <returns></returns>        public object Clone()        {            /// 方法一            //object obj = DeepClone();            /// 方法二            object obj = ObjectExtension.CopyObject<Employee>(this);            return obj;        }        /// <summary>        /// 序列化深拷贝方法        /// </summary>        /// <returns></returns>        private object DeepClone()        {            using (MemoryStream stream = new MemoryStream())            {                if (this.GetType().IsSerializable)                {                    BinaryFormatter formatter = new BinaryFormatter();                    formatter.Serialize(stream, this);                    stream.Position = 0;                    object employee = formatter.Deserialize(stream);                    return employee;                }            }            return null;        }        public override string ToString()        {            return string.Format("{0},employeeId = {1},employeeName = {2},{3}", this.GetType().Name, employeeId, employeeName, department.ToString());        }    }    public static class ObjectExtension    {        /// <summary>        /// 序列化深拷贝方法。        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="objSource"></param>        /// <returns></returns>        public static T CopyObject<T>(this object objSource)        {            using (MemoryStream stream = new MemoryStream())            {                if (objSource.GetType().IsSerializable)                {                    BinaryFormatter formatter = new BinaryFormatter();                    formatter.Serialize(stream, objSource);                    stream.Position = 0;                    return (T)formatter.Deserialize(stream);                }            }            return default(T);        }    }    #endregion    class SerializeCopy    {    }}