如何检查的对象的所有属性是否为空或空?

问题描述:

我有一个对象可以称之为对象A

I have an object lets call it ObjectA

和对象有10个物业,而这些都是所有字符串。

and that object has 10 properties and those are all strings.

 var myObject = new {Property1="",Property2="",Property3="",Property4="",...}

反正是有检查,看看所有这些特性是否为空或空?

is there anyway to check to see whether all these properties are null or empty?

因此​​,任何内置的方法,将返回true或false?

So any built-in method that would return true or false?

如果他们中的任何一个不为空或空,那么回报将是错误的。如果所有的人都为空应该返回true。

If any single of them is not null or empty then the return would be false. If all of them are empty it should return true.

我们的想法是,我不想写10 if语句来控制,如果这些属性为空或为null。

The idea is I do not want to write 10 if statement to control if those properties are empty or null.

感谢

您可以使用反射做

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

马修·沃森建议使用LINQ一种替代方案:

Matthew Watson suggested an alternative using LINQ:

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