C#深拷贝(克隆)(C# deep copy (clone))

1.深拷贝:防止在单独操作引用类型数据时,改变原有数据;

应用场景:汇总打印数据时,会进行计算,导致软件界面展示数据时,打印后和打印前展示的明细数据不相同。

/// <summary>
        /// 实体深度复制
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="RealObject"></param>
        /// <returns></returns>
        public static T Clone<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }
————————

< strong > 1. Deep copy: prevent changing the original data when operating reference type data alone

Application scenario: when summarizing print data, calculation will be performed, resulting in different detailed data displayed after printing and before printing in the software interface.

/// <summary>
        /// 实体深度复制
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="RealObject"></param>
        /// <returns></returns>
        public static T Clone<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }