/// <summary>
/// 深度克隆对象
/// </summary>
/// <typeparam name="T">要克隆的类型</typeparam>
/// <param name="obj">要克隆的实体</param>
/// <returns>返回克隆到的实体</returns>
public static T Clone<T>(this T obj)
{
object returnObj;
using (var ms = new MemoryStream())
{
//var data = new BinaryFormatter();//此方式要求被序列化对象要添加特性[Serializable],较麻烦
var data = new XmlSerializer(typeof(T));
data.Serialize(ms, obj);//序列化
ms.Seek(0, SeekOrigin.Begin);
returnObj = data.Deserialize(ms);//反序列化
ms.Close();
}
return (T)returnObj;
//此方式依赖于第三方库:Newtonsof.Json,较麻烦
//return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
//当然还可以利用反射来进行对象克隆,那就相当麻烦了,不建议!
}
标签:序列化,克隆,C#,对象,returnObj,ms,内存地址,data
From: https://www.cnblogs.com/skyrecord/p/18249379