ExpressionMapper(对象映射)
Posted .Neter
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(对象映射)的主要内容,如果未能解决你的问题,请参考以下文章
Spring MVC @Controller中转发或者重定向到其他页面的信息怎么携带和传递(Servlet API对象)HttpServletRequestHttpServletRespose(代码片