1. 程式人生 > 實用技巧 >物件是否為空的擴充套件方法

物件是否為空的擴充套件方法

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 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 = true; break; } } return res; }