zoukankan      html  css  js  c++  java
  • 两个类重复属性值复制

    核心代码

        /// <summary>
        /// 属性重复值复制
        /// </summary>
        /// <typeparam name="V">源模型</typeparam>
        /// <typeparam name="T">目标模型</typeparam>
        /// <param name="sourceList">数据源</param>
        /// <returns></returns>
        public static List<T> ConvertData<V, T>(List<V> sourceList)
        {
            List<T> list = new List<T>();
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();//获取目标模型属性
    
            foreach (V item in sourceList)
            {
                T model = Activator.CreateInstance<T>(); //创建目标模型实例
    
                for (int i = 0; i < properties.Length; i++)
                {
                    PropertyInfo[] personPro = item.GetType().GetProperties();
                    for (int j = 0; j < personPro.Length; j++)
                    {             
                        //判断目标模型的属性是不是源模型中的
                        if (properties[i].Name == personPro[j].Name && properties[i].PropertyType == personPro[j].PropertyType)
                        {
                            Object value = personPro[j].GetValue(item, null);
                            //将源模型中属性的值赋值给目标模型的属性                  
                            properties[i].SetValue(model, value, null);
                        }
                    }            
                }
                list.Add(model);
            }
            return list;
        }
    

      测试:

          类Test1

        public string ID { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Address { get; set; }
    

      类Test2

        public string ID { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
    

      调用

            List<Test1> testList = new List<Test1>
                {
                    new Test1
                    {
                        ID = "1", Name = "王二狗", Sex = "男", Address="12"
                    },
                    new Test1
                    {
                        ID = "2", Name = "王狗", Sex = "男", Address="12"
                    }
                };
            List<Test2> list = new List<Test2>();
    
            list = ConvertData<Test1, Test2>(testList);
    

      

  • 相关阅读:
    Bugku web web基础$_GET
    Bugku web 计算器
    Bugku web web2
    Bugku 杂项 宽带信息泄露
    Bugku 杂项 猜
    Bugku 杂项 又一张图片,还单纯吗
    Bugku 杂项 啊哒
    Bugku 杂项 眼见非实(ISCCCTF)
    Bugku 杂项 telnet
    Bugku 杂项 隐写
  • 原文地址:https://www.cnblogs.com/linhuide/p/6160723.html
Copyright © 2011-2022 走看看