在代码中经常会遇到需要把对象复制一遍,或者把属性名相同的值复制一遍。为了使得复制操作更加优雅,可以使用下列方式来进行复制,而不必针为每个类实现克隆操作。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
public static class DeepClone<TIn, TOut> { private static Func<TIn, TOut> _cache = null;
private static Func<TIn, TOut> GetFunc() { ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p"); List<MemberBinding> memberBindingList = new List<MemberBinding>();
Type inType = typeof(TIn); foreach (var item in typeof(TOut).GetProperties()) { if (!item.CanWrite) continue;
var prop = inType.GetProperty(item.Name); if (prop == null) continue;
MemberExpression property = Expression.Property(parameterExpression,prop); MemberBinding memberBinding = Expression.Bind(item, property); memberBindingList.Add(memberBinding); }
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray()); Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression }); return lambda.Compile(); }
public static TOut Clone(TIn tIn) { if (_cache == null) _cache = GetFunc(); return _cache(tIn); } }
|
参考
C#
快速高效率复制对象(表达式树)
C#基于表达式(Expression)实现对象深拷贝