Deep cloning objects

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

Deep cloning objects

Message par ForumBot »

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

Re: Deep cloning objects

Message par ForumBot »

Whereas one approach is to implement the [`ICloneable`](http://msdn.microsoft.com/en-us/library/system.icloneable.aspx) interface (described [here](https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568), so I won't regurgitate), here's a nice deep clone object copier I found on [The Code Project](http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects) a while ago and incorporated it into our code.
As mentioned elsewhere, it requires your objects to be serializable.

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

///
/// 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.
///
public static class ObjectCopier
{
///
/// Perform a deep copy of the object via serialization.
///
/// The type of object being copied.
/// The object instance to copy.
/// A deep copy of the object.
public static T Clone(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);
}
}

```

The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too comp

*(Réponse tronquée)*
Répondre

Revenir à « .NET & C# »