码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-19 18:42:34      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:sharp   his   people   console   ble   art   div   int   深拷贝   

 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值

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

标签:sharp   his   people   console   ble   art   div   int   深拷贝   

原文地址:http://www.cnblogs.com/littlerain1991/p/7049778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!