• Mapper(对象映射)


    只是演示反射的用法,使用反射的方式性能不好,可以使用表达式树的方式做对象映射。查看Linq分类里有相关文章

     Mapper:

    public class Mapper
        {
            private static ConcurrentDictionary<Type, PropertyInfo[]> PROPTY_CACHE = new ConcurrentDictionary<Type, PropertyInfo[]>();
            public static outT Map<inT, outT>(inT inObj) where outT : class
            {
                var inType = typeof(inT);
                var outType = typeof(outT);
                outT outObj = Activator.CreateInstance<outT>();
    
                PropertyInfo[] outProperties = PROPTY_CACHE.GetOrAdd(outType, (k) =>
                {
                    return outType.GetProperties();
                });
                PropertyInfo[] inProperties = PROPTY_CACHE.GetOrAdd(inType, (k) =>
                {
                    return inType.GetProperties();
                });
                PropertyInfo inProp = null;
                foreach (var outProp in outProperties)
                {
                    if (inProperties.Select(p=>p.Name.Equals(outProp.Name,StringComparison.CurrentCultureIgnoreCase)).Any())
                    {
                        inProp = inProperties.FirstOrDefault(p => p.Name.Equals(outProp.Name, StringComparison.CurrentCultureIgnoreCase));
                        outProp.SetValue(outObj, inProp.GetValue(inObj));
                    }
                }
                return outObj;
    
            }
        }

    客户端:

    People p = new People() { ID=1,Name="fan", Xingbie = true,Birthday=DateTime.Now,Dog=new Pet() { Name="阿黄"} };
    PeopleDTO pDTO = Mapper.Map<People, PeopleDTO>(p);
    
    
    
    
        public class People
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public bool Xingbie { get; set; }
            public DateTime Birthday { get; set; }  
            public Pet Dog { get; set; }
        }
        public class PeopleDTO
        {
            public int ID { get; set; }
            public string name { get; set; }
            public DateTime Birthday { get; set; }
            public Pet dog { get; set; }
        }
        public class Pet { 
        public string Name { get; set; }
        }
  • 相关阅读:
    初探Remoting双向通信(三)
    MySQL主从复制
    MySQL锁机制
    mySql索引
    连接池
    JDBC
    数据库建表、约束、索引
    Oracle和SQL简介
    Stream API 和 注解
    lambda表达式
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/11975486.html
Copyright © 2020-2023  润新知