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; }
        }
  • 相关阅读:
    winsows10 小技巧
    数组与智能指针
    卸载 VS2015
    Effective C++
    修改 git commit 的信息
    线程管理
    并发编程简介
    个别算法详解
    git 删除某个中间提交版本
    git 查看某一行代码的修改历史
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/11975486.html
Copyright © 2011-2022 走看看