检查 class 的所有属性是否为空

Check if all the properties of class are null

我有以下代码应该检查 class 的所有属性是否为空。我尝试了下面的代码,但没有用。为什么?

您可以制作一个 属性 IsInitialized,在内部执行此操作:

public bool IsInitialized
{
    get
    {
        return this.CellPhone == null && this.Email == null && ...;
    }
}

然后检查 属性 IsInitialized:

if (myUser == null || myUser.IsInitialized)
{ ... }

另一种选择是使用反射遍历并检查所有属性,但对我来说这似乎太过分了。此外,这使您可以自由地偏离原始设计(当您选择所有属性时,除了一个应该为 null 例如)。

    //NameSpace    
    using System.Reflection;

    //Definition
    bool IsAnyNullOrEmpty(object myObject)
    {
        foreach(PropertyInfo pi in myObject.GetType().GetProperties())
        {
            if(pi.PropertyType == typeof(string))
            {
                string value = (string)pi.GetValue(myObject);
                if(string.IsNullOrEmpty(value))
                {
                    return true;
                }
            }
        }
        return false;
    }

    //Call
    bool flag = IsAnyNullOrEmpty(objCampaign.Account);