public static class ObjectCopier
{
/// <summary>
/// /// Perform a deep Copy of the object.
/// /// </summary>
/// /// <typeparam name="T">The type of object being copied.</typeparam>
/// /// <param name="source">The object instance to copy.</param>
/// /// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{ throw new Exception("The type must be serializable."); }
// Don't serialize a null object, simply return the default for that object
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);
}
}
}
{
/// <summary>
/// /// Perform a deep Copy of the object.
/// /// </summary>
/// /// <typeparam name="T">The type of object being copied.</typeparam>
/// /// <param name="source">The object instance to copy.</param>
/// /// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{ throw new Exception("The type must be serializable."); }
// Don't serialize a null object, simply return the default for that object
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);
}
}
}
本文介绍了一个用于执行对象深拷贝的实用工具类,该工具类通过序列化和反序列化的方式实现,确保了拷贝的完整性和独立性。特别适用于需要复制复杂对象或避免原始对象被修改的情况。
1412

被折叠的 条评论
为什么被折叠?



