简单的数据映射类

看到一个关于表达式树的视频,自已默写了一下: 

 public class SimpleDtoMapper<TIn, TOut>
    {
        private static Func<TIn, TOut> _mapper;
        static SimpleDtoMapper()
        {
            var parameterExpression = Expression.Parameter(typeof(Pepole), "p");
            List<MemberBinding> bindings = new List<MemberBinding>();
            var typeIn = typeof(TIn);
            var typeOut = typeof(TOut);

            var typeOutProps = typeOut.GetProperties();
            var typeInProps = typeIn.GetProperties();
            foreach (var item in typeOutProps)
            {
                var inProp = typeInProps.FirstOrDefault(i => i.Name == item.Name);
                if (inProp != null)
                {
                    bindings.Add(Expression.Bind(item, Expression.Property(parameterExpression, inProp)));
                }
            }

            var typeOutFields = typeOut.GetFields();
            var typeInFields = typeIn.GetFields();

            foreach (var item in typeOutFields)
            {
                var inField = typeInFields.FirstOrDefault(i => i.Name == item.Name);
                if (inField != null)
                {
                    bindings.Add(Expression.Bind(item, Expression.Field(parameterExpression, inField)));
                }
            }

            Expression<Func<TIn, TOut>> copyExpression = Expression.Lambda<Func<TIn, TOut>>(
                                        Expression.MemberInit(Expression.New(typeOut), bindings.ToArray()),
                                        new ParameterExpression[1] { parameterExpression });
            _mapper = copyExpression.Compile();
        }

        public static TOut Map(TIn x)
        {

            return _mapper.Invoke(x);
        }
    }

 

上一篇:解释器模式(Interpretor)_java实现


下一篇:C# 表达式树遍历(二)