序列化实现深拷贝(小计)

 class Program
    {
        static void Main(string[] args)
        {
            var people1 = new People();
            people1.Age = 18;
            people1.IdCard = "410225";
            var departMent = new Department() { Name = "计算机" };
            people1.departMent = departMent;
            var people2 = people1.Clone();
            Console.WriteLine(people2.Age);
            Console.WriteLine(people2.IdCard);
            Console.WriteLine(people2.departMent.Name);
            Console.WriteLine("变化啦!");
            people1.Age = 18;
            people1.IdCard = "410225";
            departMent.Name = "金融"; 
            Console.WriteLine(people2.Age);
            Console.WriteLine(people2.IdCard);
            Console.WriteLine(people2.departMent.Name);
            Console.ReadLine();

        }
    }
    [Serializable]
    public class People
    {
        public int Age{get;set;}
        public string IdCard{get;set;}
        public Department departMent{get;set;}

        public People Clone()
        {
            using (Stream ms = new MemoryStream())
            {
                IFormatter forma = new BinaryFormatter();
                forma.Serialize(ms, this);
                ms.Seek(0, SeekOrigin.Begin);
                return forma.Deserialize(ms) as People;
            }
        }


    }
        [Serializable]

    public class Department
    {
        public string Name{get;set;}
    }

实现了深度拷贝,不会因为Department中的Name变化而影响Department中的Name值

转载于:https://www.cnblogs.com/littlerain1991/p/7049778.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值