首页 > 编程语言 >C#对象复制

C#对象复制

时间:2022-10-08 13:34:03浏览次数:58  
标签:return stream item C# object 对象 复制 result formatter

        /// <summary>
        /// Makes a copy from the object.
        /// Doesn't copy the reference memory, only data.
        /// </summary>
        /// <typeparam name="T">Type of the return object.</typeparam>
        /// <param name="item">Object to be copied.</param>
        /// <returns>Returns the copied object.</returns>
        public static T Clone<T>(this object item)
        {
            if (item != null)
            {
                BinaryFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();

                formatter.Serialize(stream, item);
                stream.Seek(0, SeekOrigin.Begin);

                T result = (T)formatter.Deserialize(stream);

                stream.Close();

                return result;
            }
            return default;
        }

 

标签:return,stream,item,C#,object,对象,复制,result,formatter
From: https://www.cnblogs.com/Insist-Y/p/16768653.html

相关文章