关于C#类的深拷贝的问题

时间:2023-02-07 19:56:37

       最近在对list进行add新元素时,发现add使用的是引用,因此在增加重复元素时,得使用深拷贝进行元素的复制。类对象的复制,一个个属性进行赋值略显笨拙,因此在网上找到了个通用的方法。比较好用,据称为表达树式https://www.cnblogs.com/emrys5/p/expression_trans_model.html

public static class TransExpV2<TIn, TOut>
    {

        private static readonly Func<TIn, TOut> cache = GetFunc();
        private static Func<TIn, TOut> GetFunc()
        {
            ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
            List<MemberBinding> memberBindingList = new List<MemberBinding>();

            foreach (var item in typeof(TOut).GetProperties())
            {
         if (!item.CanWrite)
              continue;

                MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                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 Trans(TIn tIn)
        {
            return cache(tIn);
        }

    }

 

  调用:StudentSecond ss= TransExpV2<Student, StudentSecond>.Trans(s);