物件是否為空的擴充套件方法
阿新 • • 發佈:2020-08-29
public static bool IsNull<T>(this T thisValue) { PropertyInfo[] rs = thisValue.GetType().GetProperties(); var res = true; foreach (PropertyInfo prop in rs) { PropertyInfo info = typeof(T).GetProperty(prop.Name);var value = info.GetValue(thisValue); var targetType = info.GetMethod.ReturnType; var defaultValue = targetType.IsValueType ? Activator.CreateInstance(targetType) : null; if (!Equals(value, defaultValue)) { res = false; break; } } return res; } public static bool NotNull<T>(this T thisValue) { PropertyInfo[] rs = thisValue.GetType().GetProperties(); var res = false; foreach (PropertyInfo prop inrs) { PropertyInfo info = typeof(T).GetProperty(prop.Name); var value = info.GetValue(thisValue); var targetType = info.GetMethod.ReturnType; var defaultValue = targetType.IsValueType ? Activator.CreateInstance(targetType) : null; if (!Equals(value, defaultValue)) { res = true; break; } } return res; }