<p>Alors qu’une approche consiste à implémenter l’interface <a href="http://msdn.microsoft.com/en-us/library/system.icloneable.aspx"><code>ICloneable</code></a> (décrite <a href="https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568">ici</a>, donc je ne vais pas la répéter), voici un joli copieur d’objets par clonage profond que j’ai trouvé sur <a href="http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects">The Code Project</a> il y a un certain temps et que j’ai intégré dans notre code.<br>
Comme mentionné ailleurs, vos objets doivent être sérialisables.</p>
<pre><code class="lang-auto">using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
/// <summary>
/// Perform a deep copy of the object via serialization.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>A deep copy of the object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", nameof(source));
}
// Don't serialize a null object, simply return the default for that object
if (ReferenceEquals(source, null)) return default;
using var stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
</code></pre>
<p>L’idée est de sérialiser votre objet puis de le désérialiser en un objet neuf. L’avantage est que vous n’avez pas à vous soucier de tout cloner lorsqu’un objet devient trop comp</p>
<p><em>(Réponse tronquée)</em></p>