对象是否为空的扩展方法

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;
        }

 

posted @ 2020-08-29 10:32  吉喆吉  阅读(185)  评论(0编辑  收藏  举报