Deep replication of Listless thanTgreater than instances with serialization of recommendations

  • 2021-12-05 07:05:16
  • OfStack

If List < T > If T in is a reference type (such as myClass class), it is written like this:


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

 {

    new myClass(),

    new myClass()

 };

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

In fact, it is a shallow replication process.

If you want to implement deep replication, you can use foreach or override the Clone () method in several ways.

But the best and most convenient method is to use "serialization".

Serialization refers to converting an object into a stream of bytes and then saving it in memory or in a database. Serialization can save the state information of an object and deserialize it back when it needs to be used. So serializing objects can store and exchange data. For example, if the web service sends, or if the application sends from this domain to another domain.

To serialize an object, you need the object to be serialized, the stream to contain the serialized object, and an Formatter. Serialization includes binary serialization and xml serialization.

For example, using XmlSerializer, the object to be copied is serialized into the stream, and then the new object is deserialized.


  /// <summary>
  ///  Serialization class 
  /// </summary>
  public class SerializLog
  {
    //1. It is done by serialization   Object that references the object   Deep replication   Is the best way 
    //2. Below  Clone Method, I need to use the   Generic object   As a parameter, the  Clone You need to wear it in the back <T> Otherwise compile error 
    
    public static T Clone<T>(T realObject) // T  Objects to serialize 
    {
      using (Stream stream = new MemoryStream()) //  Initialization 1 A   Stream object 
      {
        XmlSerializer serializer = new XmlSerializer(typeof(T)); // The object to be serialized is serialized to the xml Documentation ( Formatter ) 
        serializer.Serialize(stream, realObject); // Writes the sequenced object to the stream 
        stream.Seek(0, SeekOrigin.Begin);     
        return (T)serializer.Deserialize(stream);//  Deserialize to get a new object 
      }
    }
  }


Related articles: