List<T> 深度拷贝

        /// <summary>
        /// 不带[Serializable]标识的深度拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepCopy<T>(this T obj) where T : class
        {
            object retval = null;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(T));
                xml.Serialize(ms, obj);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                retval = xml.Deserialize(ms);
                ms.Close();
            }
            return (T)retval;
        }

        /// <summary>
        /// 带有[Serializable]标识的深度拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<T> Clone<T>(this List<T> obj) where T : class
        {
            using (System.IO.Stream objectStream = new System.IO.MemoryStream())
            {
                System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(objectStream, obj);
                objectStream.Seek(0, System.IO.SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as List<T>;
            }
        }

 

posted @ 2021-02-28 23:18  devs  阅读(97)  评论(0编辑  收藏  举报