Several methods to realize deep copy (clone/copy) of entity objects in .NET[C#]

Several methods to realize deep copy (clone/copy) of entity objects in .NET[C#]

There are several ways to implement deep copy (clone/copy) of entity objects in .NET[C#], there is always one suitable for you.

Way one uses binary stream

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

///<summary>
///Refer to http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
///</summary>
public static class ObjectCopier
{
    public static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }

        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}

Method two use serialization and deserialization

public static T CloneJson<T>(this T source)
{            
    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

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

Way three using reflection

public static T DeepCopyByReflect<T>(T obj)
{
   //If it is a string or value type, return directly
    if (obj is string || obj.GetType().IsValueType) return obj;
    object retval = Activator.CreateInstance(obj.GetType());
    FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
    foreach (FieldInfo field in fields)
    {
        try {field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj)));}
        catch {}
    }
    return (T)retval;
}

Method four use XML serialization and deserialization

public static T DeserializeXML<T>(string xmlData) where T:new()
    {
        if (string.IsNullOrEmpty(xmlData))
            return default(T);

        TextReader tr = new StringReader(xmlData);
        T DocItms = new T();
        XmlSerializer xms = new XmlSerializer(DocItms.GetType());
        DocItms = (T)xms.Deserialize(tr);

        return DocItms == null? default(T): DocItms;
    }

From FIG sharing network -> "Several methods .NET [C #] to achieve a deep copy entity object (clone/copy) of"

Reference: https://cloud.tencent.com/developer/article/1034516 .NET[C#] Several methods to realize deep copy (clone/copy) of entity objects-Cloud + Community-Tencent Cloud