Files
Atomx/Atomx.Utils/Extension/ObjectExtension.cs
2025-12-02 13:10:10 +08:00

47 lines
1.3 KiB
C#

using System.Reflection;
using System.Xml.Serialization;
namespace Atomx.Utils.Extension
{
public static class ObjectExtension
{
/// <summary>
/// 利用反射实现深拷贝
/// </summary>
/// <param name="_object"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 深度克隆对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T Clone<T>(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;
}
}
}