如何检查的对象的所有属性是否为空或空? [英] How to check all properties of an object whether null or empty?

查看:118
本文介绍了如何检查的对象的所有属性是否为空或空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象可以称之为对象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));

这篇关于如何检查的对象的所有属性是否为空或空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆