using System.Linq.Expressions;
namespace PLCSharp.Core.Tools
{
///
/// Copy
///
public static class Copy
{
private static readonly Dictionary _cache = [];
///
/// DeepCopy
///
/// obj
/// 返回结果
public static T DeepCopy(this T obj)
{
if (obj == null) return default;
var type = typeof(T);
if (!_cache.TryGetValue(type, out var func))
{
var parameter = Expression.Parameter(type, "p");
var bindings = new List();
foreach (var property in type.GetProperties())
{
if (property.CanWrite)
{
var propertyAccess = Expression.Property(parameter, property);
var binding = Expression.Bind(property, propertyAccess);
bindings.Add(binding);
}
}
var memberInit = Expression.MemberInit(Expression.New(type), bindings);
var lambda = Expression.Lambda>(memberInit, parameter);
func = lambda.Compile();
_cache[type] = func;
}
return ((Func)func)(obj);
}
}
}