runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

-- 

 

/// <summary>
        /// 将T1 实体的参数复制给 T2 ,不能处理多层次
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        public static void CopyModel<T1, T2>(T1 a, T2 b)
        {

            System.Reflection.PropertyInfo[] cfgItemProperties = a.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            foreach (System.Reflection.PropertyInfo item in cfgItemProperties)
            {
                string name = item.Name;
                object value = item.GetValue(a, null);
                //string 或 值属性,且value 不为 null
                if ((item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) && value != null && !string.IsNullOrEmpty(value.ToString()))
                {
                    #region 在MODEL2中查找是否有此参数名,有则赋值
                    System.Reflection.PropertyInfo[] list2 = b.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    foreach (System.Reflection.PropertyInfo i2 in list2)
                    {
                        //两者 PropertyType.Name  要相等
                        if (item.Name == i2.Name && item.PropertyType.Name == i2.PropertyType.Name)
                        {
                            i2.SetValue(b, value, null);
                        }
                    }
                    #endregion

                }
            }


        }

 

 

--

posted on 2019-04-25 10:56  runliuv  阅读(1049)  评论(0编辑  收藏  举报