ExpressionMapper(对象映射)

 

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

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(对象映射)

上一篇:[React] Setup an API Proxy in Create React App


下一篇:bug 记录 Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans