In the process of daily coding, we often encounter some small operations, and sometimes we just want to make an appointment (tōu) about (gè) time (lǎn) between (er), so writing tool methods is convenient to call directly
1 public static class WipeNullHelper 2 { 3 /// <summary> 4 /// Change the null in the object to the default value of the corresponding type 5 /// </summary> 6 /// <param name="entity"> Object entity </param> 7 /// <returns></returns> 8 public static T WipeNull<T> (T entity) 9 { 10 System.Reflection.PropertyInfo[] ps = entity.GetType().GetProperties() ; 11 Type type = entity.GetType(); 12 foreach (PropertyInfo propertie in ps) 13 { 14 if (propertie.PropertyType == typeof(string)) 15 { 16 PropertyInfo propertyInfo = type.GetProperty(propertie.Name); 17 if (propertyInfo.GetValue(entity, null) == null) 18 { 19 propertyInfo.SetValue(entity, "", null); 20 } 21 } 22 else if (propertie.PropertyType == typeof(Int32)) 23 { 24 PropertyInfo propertyInfo = type.GetProperty(propertie.Name); 25 if (propertyInfo.GetValue(entity, null) == null) 26 { 27 propertyInfo.SetValue(entity, 0, null); 28 } 29 } 30 else if (propertie.PropertyType == typeof(Nullable<int>)) 31 { 32 PropertyInfo propertyInfo = type.GetProperty(propertie.Name); 33 if (propertyInfo.GetValue(entity, null) == null) 34 { 35 propertyInfo.SetValue(entity, 0, null); 36 } 37 } 38 else if (propertie.PropertyType == typeof(decimal)) 39 { 40 PropertyInfo propertyInfo = type.GetProperty(propertie.Name); 41 if (propertyInfo.GetValue(entity, null) == null) 42 { 43 propertyInfo.SetValue(entity, Convert.ToDecimal(0.0), null); 44 } 45 } 46 else if (propertie.PropertyType == typeof(Nullable<decimal>)) 47 { 48 PropertyInfo propertyInfo = type.GetProperty(propertie.Name); 49 if (propertyInfo.GetValue(entity, null) == null) 50 { 51 propertyInfo.SetValue(entity, Convert.ToDecimal(0.0), null); 52 } 53 } 54 } 55 return entity; 56 } 57 58 }