/// <summary>
/// 深拷贝
/// 注意:T必须标识为可序列化[Serializable]
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T DeepCopy<T>(this T obj)
where T : class
{
try
{
if (obj == null)
{
return null;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
binaryFormatter.Serialize(stream, obj);
stream.Position = 0;
return (T)binaryFormatter.Deserialize(stream);
}
}
catch
{
return null;
}
}
注意:
1.上述方法中,限定泛型T为引用类型,因为值类型本身不需要深拷贝;
2.类型T必须标明可序列化,即类前面添加特性[Serializable]。