using System.Reflection;
using System.Xml.Serialization;
namespace Atomx.Utils.Extension
{
public static class ObjectExtension
{
///
/// 利用反射实现深拷贝
///
///
///
public static object DeepCopy(object _object)
{
Type T = _object.GetType();
object o = Activator.CreateInstance(T);
PropertyInfo[] PI = T.GetProperties();
for (int i = 0; i < PI.Length; i++)
{
PropertyInfo P = PI[i];
P.SetValue(o, P.GetValue(_object));
}
return o;
}
///
/// 深度克隆对象
///
///
///
///
public static T Clone(this T obj)
{
T ret = default;
if (obj != null)
{
XmlSerializer cloner = new XmlSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
cloner.Serialize(stream, obj);
stream.Seek(0, SeekOrigin.Begin);
ret = (T)cloner.Deserialize(stream);
}
return ret;
}
}
}