English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementing Deep Copy of List<T> Instances Using Serialization (Recommended)

If the T in List<T> is a reference type (such as the myClass class), then in this kind of writing:

 List<myClass> lists1 = new List<myClass>()
 {
    new myClass(),
    new myClass()
 };

List<myClass> lists2 = new List<myClass>(lists1 );

It is actually a shallow copy process.

If you want to achieve deep copy, there are several ways to do it, such as using foreach, or rewriting the Clone() method.

But the best and most convenient method is still to use the [Serialization] method to implement it.

Serialization refers to the process of converting an object into a byte stream format and then storing it in memory or a database. Serialization can save the state information of an object, which can be deserialized back when needed. Therefore, serializing an object can store and exchange data. For example, if a web service sends it, or the application sends it from one domain to another.

To serialize an object, you need the object to be serialized, the stream that needs to contain the serialized object, and a Formatter. Serialization includes: binary serialization and XML serialization.

For example, use XmlSerializer to serialize the object to be copied into the stream, and then get a new object through deserialization.

  /// <summary>
  /// Serialization class
  /// </summary>
  public class SerializLog
  {
    //1.Using serialization to complete the deep copy of the reference object is the best way
    //2.The Clone method needs to use a generic object as a parameter, so the <T> declaration needs to be added after Clone, otherwise the compilation will fail
    public static T Clone<T>(T realObject) // T The object to be serialized
    {
      using (Stream stream = new MemoryStream()) // Initialize a stream object
      {
        XmlSerializer serializer = new XmlSerializer(typeof(T)); //Serialize the object to be serialized into an XML document (Formatter)
        serializer.Serialize(stream, realObject); //Write the serialized object to the stream
        stream.Seek(0, SeekOrigin.Begin);     
        return (T)serializer.Deserialize(stream);// Deserialize to get a new object
      }
    }
  }

The following article uses serialization to implement List The deep copy of the instance (recommended) is all the content that the editor shares with everyone. I hope it can provide a reference for everyone, and I also hope everyone will support the Yelling Tutorial more.

You May Also Like