• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
【我是谁】
博客园    首页    新随笔    联系   管理    订阅  订阅

深拷贝-浅拷贝

深拷贝-浅拷贝的概念就不说了,基础的东西! 实现如下:

public class Person
    {
        public string Name
        {
            get;
            set;
        }
       
    
        public Car Car
        {
            get;
            set;
        }

        public Person ShallowClone()
        {
            //一句话实现浅拷贝。Object的方法
            return this.MemberwiseClone() as Person;

            //MemberwiseClone的作用就是把当前对象浅拷贝一份。
        }

        //通过序列化与反序列化会将当前对象实现一次深拷贝
        public Person DeepClone()
        {
            //类需要Serializable
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, this);
                ms.Position = 0;
                return bf.Deserialize(ms) as Person;
            }
        }


    }
    public class Car
    {
        public string Color
        {
            get;
            set;
        }
    }

  

posted @ 2017-12-09 18:00  【我是谁】  阅读(107)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3