【ExpressionMapper(对象映射)】青春须早为,岂能长少年。这篇文章主要讲述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); }}
推荐阅读
- 微信小程序自定义转发设置 onShareAppMessage
- 2018开发最快的Webapp框架--BUI交互框架
- bug 记录 Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory be
- 微信小程序npm引入vant-weapp库的方法
- Android中的网络编程
- App端异常,性能监控及定位分析
- 2020年 VMware Center Server Appliance VCSA 7.0 安装部署
- App接口消息推送
- Linux/安卓驱动入门视频