生成表达式目录树 泛型缓存

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Linq.Expressions;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace ExpressionDemo.MappingExtend
 9 {
10     /// <summary>
11     /// 生成表达式目录树  泛型缓存
12     /// </summary>
13     /// <typeparam name="TIn"></typeparam>
14     /// <typeparam name="TOut"></typeparam>
15     public class ExpressionGenericMapper<TIn, TOut>//Mapper`2
16     {
17         private static Func<TIn, TOut> _FUNC = null;
18         static ExpressionGenericMapper()
19         {
20             ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
21             List<MemberBinding> memberBindingList = new List<MemberBinding>();
22             foreach (var item in typeof(TOut).GetProperties())
23             {
24                 MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
25                 MemberBinding memberBinding = Expression.Bind(item, property);
26                 memberBindingList.Add(memberBinding);
27             }
28             foreach (var item in typeof(TOut).GetFields())
29             {
30                 MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));
31                 MemberBinding memberBinding = Expression.Bind(item, property);
32                 memberBindingList.Add(memberBinding);
33             }
34             MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
35             Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[]
36             {
37                     parameterExpression
38             });
39             _FUNC = lambda.Compile();//拼装是一次性的
40         }
41         public static TOut Trans(TIn t)
42         {
43             return _FUNC(t);
44         }
45     }
46 }

 

上一篇:在Linux(Luna)下向Launch启动器中添加图标


下一篇:Expression Tree 遍历集合