• 两个类重复属性值复制


    核心代码

        /// <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);
    

      

  • 相关阅读:
    nginx 详解
    阿里云 消息队列mq
    手机浏览器Yandex安装插件说明
    windows下JAVA环境变量配置
    共享文件夹免密登入
    自动添加静态路由
    加入WSUS补丁服务器并下载补丁
    加入时间同步服务器(NTP)
    更改rdp端口
    关闭及开启445等危险端口
  • 原文地址:https://www.cnblogs.com/linhuide/p/6160723.html
Copyright © 2020-2023  润新知