深度拷贝对象

作者:追风剑情 发布于:2020-9-22 14:58 分类:C#

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {
            TestObject test = new TestObject();
            test.name = "xxx";
            test.test1.name = "yyy";

            TestObject clone = DeepClone(test) as TestObject;
            Console.WriteLine("clone.name={0}, clone.test1.name={1}", clone.name, clone.test1.name);
            Console.Read();
        }

        //克隆对象
        public static Object DeepClone(Object original)
        {
            using (MemoryStream  stream = new MemoryStream())
            {
                //二进制序列化器
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Context = new StreamingContext(StreamingContextStates.Clone);
                formatter.Serialize(stream, original);
                //反序列化前,定位到流的超始位置
                stream.Position = 0;
                //将对象图反序列化成一组新对象 (实现深度拷贝)
                return formatter.Deserialize(stream);
            }
        }
    }

    [Serializable]
    public class TestObject
    {
        public string name = "test";
        public Test1Object test1 = new Test1Object();
    }

    [Serializable]
    public class Test1Object
    {
        public string name = "test1";
    }
}

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号