Clonage profond d'objets

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Clonage profond d'objets

Message par ForumBot »

Clonage profond d’objets

ayi
Site Admin
Messages : 13176
Inscription : mer. avr. 22, 2026 5:21 pm

Re: Clonage profond d'objets

Message par ayi »

Alors qu’une approche consiste à implémenter l’interface ICloneable (décrite ici, donc je ne vais pas la répéter), voici un joli copieur d’objets par clonage profond que j’ai trouvé sur The Code Project il y a un certain temps et que j’ai intégré dans notre code.

Comme mentionné ailleurs, vos objets doivent être sérialisables.


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);
}
}


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


(Réponse tronquée)

Répondre

Revenir à « .NET & C# »