C#通过序列化实现深表复制

利用二进制序列化的方式进行深拷贝  有一个缺陷 序列化的类型必须标识为刻序列化的[Serializable] 否则无法进行二进制序列化

class Program
    {
        static void Main(string[] args)
        {
            Person P = new Person("小丽",20);
            Person N = (Person)DeepCopy(P);
            P.Grade = 200;
            Console.WriteLine(N.Grade.ToString());
            Console.ReadKey();
        }
        /// <summary>
        /// 利用序列化实现深拷贝
        /// </summary>
        /// <param name="_obj"></param>
        /// <returns></returns>
        static object DeepCopy(object _obj)
        {
            BinaryFormatter BF2 = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
               BF2.Serialize(stream,_obj);
               stream.Position = 0;
               return BF2.Deserialize(stream);
            }
        }
    }
    [Serializable]
    class Person
    {
        private string mName;
        private int mGrade;
        public int Grade
        {
            get { return mGrade; }
            set { mGrade = value; }
        }
        public string Name
        {
            get { return mName; }
            set { mName = value; }
        }
        public Person(string _Name, int _Grade)
        {
            mName = _Name;
            mGrade = _Grade;
        }
        public Person()
        {


        }
    }

 

 

摘自csdn-hzq354242

posted @ 2018-02-27 14:01  弥行  阅读(205)  评论(0编辑  收藏  举报