zoukankan      html  css  js  c++  java
  • 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; }
        }
  • 相关阅读:
    wiki iso88591字符表的解释
    [c]字符1一维数组求长度
    vim 用户配置
    PHP中向浏览器输出图片
    如何及时取消 BackgroundWorker 组件的后台工作
    python basic
    php5.1中的时区设置。
    MyBatis的深入原理分析之1架构设计以及实例分析
    hibernate缓存:一级缓存和二级缓存
    Spring 注解(Annotation)代替XML实现零配置
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/11975486.html
Copyright © 2011-2022 走看看