其他分享
首页 > 其他分享> > 简单的数据映射类

简单的数据映射类

作者:互联网

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

 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);
        }
    }

 

标签:Name,映射,数据,parameterExpression,item,简单,var,bindings,Expression
来源: https://www.cnblogs.com/yangzn/p/14320510.html