C#的对象深拷贝

转自: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();
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值