[. Net Core] [4] shallow copy and deep copy

1, Foreword

During the development process, we often encounter the copy of an object class of a reference type. We can get a new backup real column and modify it without affecting the original object instance. There are usually two kinds: shallow copy and deep copy.

2, Serialization tag

Mark the object class to be copied as Serializable. It seems that there is no problem during the test.

 [Serializable] //The test process marked serializable found that there seemed to be no problem
 public class DeviceLocation : ICloneable
    {
        public Device Device { get; set; }       
        public int Age { get; set; }
    }      
   
 public class Device
   {
 		public string {get;set;}
   }  

3, Shallow copy replication

For Object1 and Object2 before and after copying, the value type Age in the two objects does not affect each other, but the reference type Device in the Object still points to the same address. If you change the Device property of one Object, the Device in the other Object will also change synchronously.

Shallow copy individuals are usually used in. netcore EntityFrameworkCore database query. A record Entity queried from the database is bound with database tag status. After directly changing the Entity, it may be automatically saved back to the database table. Obviously, this is not what we expect. At this time, shallow copy can be used, Get this record and modify it by yourself. [when the domain layer directly queries a record Entity without Dto conversion]

 public class DeviceLocation : ICloneable
    {
        public Device Device { get; set; }       
        public int Age { get; set; }
    }   

   /// <summary>
   ///Shallow copy: used to query the reference copy from the database
   /// </summary>
   /// <returns></returns>
   public object Clone()
   {
       return this.MemberwiseClone();
   }

   /// <summary>
   ///Shallow copy: used to query the reference copy from the database
   /// </summary>
   /// <returns></returns>
   public DeviceLocation ShallowClone()
   {
       return this.Clone() as DeviceLocation;
   }

4, Deep copy replication:. Net before version 5

Completely copy an unrelated object with permissions, regardless of whether there are nested objects in the object.

 [Serializable]
 public class DeviceLocation
    {
        public Device Device { get; set; }       
        public int Age { get; set; }

	    /// <summary>
	    ///Deep copy: for the. Net version before version 5, the new version is outdated
    	/// </summary>
	    /// <returns></returns>
    	public DeviceLocation DeepClone()
	    {
    	    using (System.IO.Stream os = new System.IO.MemoryStream())
        	{
            	System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
	            formatter.Serialize(os, this);
    	        os.Seek(0, System.IO.SeekOrigin.Begin);
        	    return formatter.Deserialize(os) as DeviceLocation;
	        }
    	}
    }   

5, Deep copy replication:. net core after. net 5

Completely copy an unrelated object with permissions, regardless of whether there are nested objects in the object.

 [Serializable]
 public class DeviceLocation
    {
        public Device Device { get; set; }       
        public int Age { get; set; }

	    /// <summary>
	    ///Deep copy: nested objects are also completely independent
	    /// </summary>
	    /// <returns></returns>
	    public ICruiseHelper DeepClone()
	    {
     	   var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
	       var serializeSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
    	   return JsonConvert.DeserializeObject<DeviceLocation>(JsonConvert.SerializeObject(this, serializeSettings), deserializeSettings);
	    }

    }   

6, Deep copy replication: independent encapsulation

    /// <summary>
	///Deep clone helper class
	/// </summary>
	public static class CloneHelper
	{
		/// <summary>
		///Deep cloning
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="source"></param>
		/// <returns></returns>
		public static T DeepClone<T>(this T source)
		{
			// Don't serialize a null object, simply return the default for that object
			if (Object.ReferenceEquals(source, null))
			{
				return default(T);
			}

			var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
			var serializeSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
			return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, serializeSettings), deserializeSettings);
		}
	}

7, Summary

In the past two days, the prompt of using deep copy in. netcore is outdated and confused. It took a long time to search the Internet to find relevant materials. Remember to collect and praise if useful.

Tags: C# .NET

Posted on Mon, 20 Sep 2021 21:03:47 -0400 by madchops