實體類相同屬性間賦值與如何判斷實體類中是否全部的字段都爲null

1,實體類相同屬性間賦值
/// <summary>
        /// 將實體2的值動態賦值給實體1(名稱同樣的屬性進行賦值)
        /// </summary>
        /// <param name="model1">實體1</param>
        /// <param name="model2">實體2</param>
        /// <returns>賦值後的model1</returns>
        protected static T1 BindModelValue<T1, T2>(T1 model1, T2 model2) where T1 : class where T2 : class
        {
            if (model2 != null)
            {
                Type t1 = model1.GetType();
                Type t2 = model2.GetType();
                PropertyInfo[] property2 = t2.GetProperties();
                //排除主鍵
                List<string> exclude = new List<string>() { "Id" };
                foreach (PropertyInfo p in property2)
                {
                    if (exclude.Contains(p.Name)) { continue; }
                    t1.GetProperty(p.Name)?.SetValue(model1, p.GetValue(model2, null));
                }
                return model1;
            }
            return null;
        }
View Code
二、判斷實體類中是否全部的字段都爲null
 public static Boolean IsPropNull(Object obj)
        {
            Type t = obj.GetType();
            PropertyInfo[] props = t.GetProperties();
            foreach (var item in props)
            {
                //排除主鍵id
                if (item.Name == "Id") { continue; }
                //一旦有不爲null的值,就返回true
                if (item.GetValue(obj) != null)
                {
                    return true;
                }
            }
            return false;
        }
View Code
相關文章
相關標籤/搜索