C#对象深表复制方法

2021-05-29 15:04

阅读:1242

标签:lam   style   bsp   instance   com   foreach   序列化   col   convert   

 //反射
        public static TOut TransReflection(TIn tIn)
        {
            TOut tOut = Activator.CreateInstance();
            var tInType = tIn.GetType();
            foreach (var itemOut in tOut.GetType().GetProperties())
            {
                var itemIn = tInType.GetProperty(itemOut.Name); ;
                if (itemIn != null)
                {
                    itemOut.SetValue(tOut, itemIn.GetValue(tIn,null),null);
                }
            }
            return tOut;
        }

        //序列化
        public static TOut TransJsonConvert(TIn tIn)
        {           
            return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(tIn));
        }
using System.Linq.Expressions;
 /// 
    /// 表达式树实现的深表复制
    /// 
    /// 
    /// 
    public static class TransExp
    {

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

            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> lambda = Expression.Lambda>(memberInitExpression, new ParameterExpression[] { parameterExpression });

            return lambda.Compile();
        }

        public static TOut Trans(TIn tIn)
        {
            return cache(tIn);
        }
    }

 

C#对象深表复制方法

标签:lam   style   bsp   instance   com   foreach   序列化   col   convert   

原文地址:https://www.cnblogs.com/taofengfeng/p/11095467.html


评论


亲,登录后才可以留言!