Deep copy and shallow copy of the class (no ICloneable required)

Shallow copy:

        public classname Clone()
         {
    
    
             return (classname)this.MemberwiseClone();
         }

Deep copy (serialization + deserialization) (reflection and one-to-one assignment can also be used):

 	public classname DeepClone()
        {
    
    
            using (Stream stream = new MemoryStream())
            {
    
    
                BinaryFormatter bFormatter = new BinaryFormatter();
                bFormatter.Serialize(stream, this);
                stream.Seek(0, SeekOrigin.Begin);
                return (classname)bFormatter.Deserialize(stream);
            }            
        }

Guess you like

Origin blog.csdn.net/tianxiefenxiang/article/details/106838411