保证对象里所有属性都有值

        /// <summary>
        /// 设置对象中为空的属性值,即对象的所有属性均有值(集合数组属性不能设置)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">数据源</param>
        /// <param name="target">新对象</param>
        public static void SetFullObject<T>(T source, T target) where T : class
        {
            Type type = source.GetType(); 
            var properties = type.GetRuntimeProperties().ToList();
            foreach (var property in properties)
            { 
                if (property.GetValue(source) == null)
                {
                    property.SetValue(target, "-1");
                }
                else if (property.GetValue(source).ToString() == "")
                {
                    property.SetValue(target, "-1");
                }
                else
                {
                    property.SetValue(target, property.GetValue(source));
                }
            }
        }

 

posted @ 2021-07-08 08:42  超级驼鹿  阅读(98)  评论(0编辑  收藏  举报
/*