簡體   English   中英

檢查類的任何屬性是否為null

[英]Check if any property of class is null

我有以下課程: -

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

但是在調試的過程中,我發現每次屬性都是否為Null時它是否為true。

請幫助我如何通過Avoioding For/foreach循環實現這一Avoioding For/foreach

您正在檢查屬性本身是否為null(永遠不會為真),而不是屬性的值。 請改用:

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

這可能對你有所幫助

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

我使用對象的下面擴展,我用它來驗證我不希望所有屬性為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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM