C#的对象深拷贝

时间:2022-10-02 19:56:06

转自:http://www.cnblogs.com/Yjianyong/archive/2010/08/05/1793066.html

用序列化和反序列化的方法来实现对对象的深拷贝。

public static T DeepCopy<t>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
//序列化成流
bf.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
//反序列化成对象
retval = bf.Deserialize(ms);
ms.Close();
}
return (T)retval;
}

通过序列化为 Base64String 的形式还复制:对于包含图片等Bit字节之类的实体,直接通过上方法复制出来的实体结果不正确(知道原因的朋友敬请评论),可以通过转化为Base64String的形式,就可以得到正确的结果,对保存到数据库也比较方便。

/// <summary>
/// 复制控件。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializeObj"></param>
/// <returns></returns>
public static T GetObjectClone<T>(T serializeObj)
{
string base64String = SerializeObject<T>(serializeObj);
return DeserializeObject<T>(base64String);
}

/// <summary>
/// 序列化为Base64String。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializeObj"></param>
/// <returns></returns>
public static string SerializeObject<T>(T serializeObj)
{
string base64String = string.Empty;
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(ms, serializeObj);
base64String = Convert.ToBase64String(ms.GetBuffer());
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
ms.Close();
}
return base64String;
}

/// <summary>
/// 从Base64反序列化。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="base64String"></param>
/// <returns></returns>
public static T DeserializeObject<T>(string base64String)
{
MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64String));
BinaryFormatter formatter = new BinaryFormatter();

try
{
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
return (T)formatter.Deserialize(ms);
}
catch (Exception e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
ms.Close();
}
}