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

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

问题描述

我有一个对象可以叫它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?

如果其中任何一个不为 null 或为空,则返回为 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 语句来控制这些属性是空的还是空的.

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

谢谢

推荐答案

您可以使用 Reflection

You can do it using Reflection

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

Matthew Watson 提出了使用 LINQ 的替代方案:

Matthew Watson suggested an alternative using LINQ:

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

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

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