码迷,mamicode.com
首页 > 其他好文 > 详细

映射对象

时间:2019-01-29 01:16:54      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:typeof   复制   for   code   summary   pre   setvalue   target   framework   

需要把一个对象映射成另一个对象的时候,这个需要用到反射,一般是数据库中的表的列不够,还需要别的列,这个时候可以把定义一个对象把所有的列都定义了,然后把数据库的表赋值给这个对象,然后再根据需求加上别的列来用。

https://docs.microsoft.com/en-us/dotnet/api/system.reflection?view=netframework-4.7.2

方法: 

  /// <summary>
        /// 将一个对象复制给另一个对象
        /// </summary>
        /// <typeparam name="T">返回的对象类型</typeparam>
        /// <typeparam name="X">原始对象类型</typeparam>
        /// <param name="x">原始对象</param>
        /// <returns>返回T类型对象</returns>
        public static T Mapper<T, X>(X x)
        {
            T t = Activator.CreateInstance<T>(); //创建返回的类型
            var typeParent = t.GetType();//获取返回类型 ==typeof(t)
            var typeSub = x.GetType(); //获取原始对象类型
            foreach (PropertyInfo sp in typeSub.GetProperties())//获得类型的属性字段  
            {
                foreach (PropertyInfo dp in typeParent.GetProperties())
                {
                    if (dp.Name == sp.Name)//判断属性名是否相同  
                    {
                        dp.SetValue(t, sp.GetValue(x, null), null);//获得原对象属性的值复制给新对象的属性  
                    }
                }
            }
            return t;
        }
    public class TestOld
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int? Age { get; set; }
    }

    public class TestNew
    {
        public int ID { get; set; }      

        public string Name { get; set; }

        public int? Age { get; set; }

        public bool? Sex { get; set; }
    }

技术分享图片

 

映射对象

标签:typeof   复制   for   code   summary   pre   setvalue   target   framework   

原文地址:https://www.cnblogs.com/Sea1ee/p/10332280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!