检查类的任何属性是否为null

时间:2016-12-22 04:27:44

标签: c# asp.net .net

我有以下课程: -

public class Requirements
    {
        public string EventMessageUId { get; set; }
        public string ProjectId { get; set; }        
        public List<Message> Message { get; set; }        
    }

我正在将它映射到Json: -

Requirements objRequirement = JsonObject.ToObject<Requirements>();

我想检查类的任何属性是否没有值,或者在上面的映射后保留为null。

为此,我尝试了: -

bool isNull= objRequirement.GetType().GetProperties().All(p => p != null);

但是在调试过程中,我发现每次属性都是否为空时,它是否为真值。

请帮助我如何通过Avoioding For/foreach循环实现此目的。

3 个答案:

答案 0 :(得分:17)

您正在检查属性本身是否为空(永远不会为真),而不是属性的值。请改用:

bool isNull = objRequirement.GetType().GetProperties()
                            .All(p => p.GetValue(objRequirement) != null);

答案 1 :(得分:2)

这可能会为你做到这一点

objRequirement.GetType().GetProperties()
.Where(pi => pi.GetValue(objRequirement) is string)
.Select(pi => (string) pi.GetValue(objRequirement))
.Any(value => String.IsNullOrEmpty(value));

答案 2 :(得分:1)

我使用该对象的以下扩展名,该扩展名用于验证那些我不希望所有属性都为null或为空的对象,以便保存对数据库的某些调用。我认为它也适合您的情况。

    /// <summary>
    /// Returns true is all the properties of the object are null, empty or "smaller or equal to" zero (for int and double)
    /// </summary>
    /// <param name="obj">Any type of object</param>
    /// <returns></returns>
    public static bool IsObjectEmpty(this object obj)
    {
        if (Object.ReferenceEquals(obj, null))
            return true;

        return obj.GetType().GetProperties()
            .All(x => IsNullOrEmpty(x.GetValue(obj)));
    }

    /// <summary>
    /// Checks if the property value is null, empty or "smaller or equal to" zero (for numeric types)
    /// </summary>
    /// <param name="value">The property value</param>
    /// <returns></returns>
    private static bool IsNullOrEmpty(object value)
    {
        if (Object.ReferenceEquals(value, null))
            return true;

        if (value.GetType().GetTypeInfo().IsClass)
            return value.IsObjectEmpty();

        if (value is string || value is char || value is short)
            return string.IsNullOrEmpty((string) value);

        if (value is int)
            return ((int) value) <= 0;

        if (value is double)
            return ((double) value) <= 0;

        if (value is decimal)
            return ((decimal) value) <= 0;

        if (value is DateTime)
            return false;

        // ........
        // Add all other cases that we may need
        // ........

        if (value is object)
            return value.IsObjectEmpty();

        var type = value.GetType();
        return type.IsValueType
            && Object.Equals(value, Activator.CreateInstance(type));
    }

通话显然是obj.IsObjectEmpty()