美文网首页
C#深度拷贝,浅拷贝

C#深度拷贝,浅拷贝

作者: 晓龙酱 | 来源:发表于2017-09-18 10:32 被阅读12次

    使用序列化的方法实现深度拷贝非常方便

    using System;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    
    <font color=blue>[Serializable]</font>
    class Person : ICloneable
    {
        public object Clone()
        {
            return this.MemberwiseClone();
        }
    
        public Person DeepClone()
        {
            using(Stream os = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter(); 
                formatter.Serialize(os, this);
                os.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(os) as Person;
            }
        }
    
        public Person ShallowClone()
        {
            return Clone() as Person;
        }
    }
    

    相关文章

      网友评论

          本文标题:C#深度拷贝,浅拷贝

          本文链接:https://www.haomeiwen.com/subject/wabvsxtx.html