码迷,mamicode.com
首页 > 移动开发 > 详细

ExpressionMapper(对象映射)

时间:2020-05-05 01:07:40      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:new   cache   ESS   member   current   使用   private   stat   inf   

 

性能仅次于硬编码,推荐使用

public static class ExpressionMapper<TIn, TOut>
    {
        private static readonly ConcurrentDictionary<string, Func<TIn, TOut>> CACHE = new ConcurrentDictionary<string, Func<TIn, TOut>>();

        public static TOut Trans(TIn tIn)
        {
            string cacheName = $"cache_{typeof(TIn).FullName}_{typeof(TOut).FullName}";
            Func<TIn, TOut> func = CACHE.GetOrAdd(cacheName, key => {
                ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
                List<MemberBinding> memberBindingList = new List<MemberBinding>();
                PropertyInfo inProperty = null;
                foreach (var item in typeof(TOut).GetProperties())
                {
                    if (!item.CanWrite) continue;
                    inProperty = typeof(TIn).GetProperty(item.Name);
                    if (inProperty!=null)
                    {
                        MemberExpression property = Expression.Property(parameterExpression, inProperty);
                        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();
            });
            return func(tIn);
        }

    }

 

ExpressionMapper(对象映射)

标签:new   cache   ESS   member   current   使用   private   stat   inf   

原文地址:https://www.cnblogs.com/fanfan-90/p/12828967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!