类的深拷贝和浅拷贝(不需要ICloneable)

浅拷贝:

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

深拷贝(序列化+反序列化)(也可以用反射、一对一赋值):

 	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);
            }            
        }

猜你喜欢

转载自blog.csdn.net/tianxiefenxiang/article/details/106838411