我有一个对象,我们称之为ObjectA
,该对象有 10 个都是字符串的属性。
var myObject = new {Property1="",Property2="",Property3="",Property4="",...}
是否有办法检查所有这些属性是否为 null 或为空?
任何内置方法会返回 true 或 false?
如果其中任何一个不为 null 或空,则返回 false,如果全部为空,则返回 true。
我只是想避免编写 10 个 if 语句来控制每个属性为空或 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;
}
马修·沃森(Matthew Watson)建议使用另一种方法LINQ
:
return myObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => (string)pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)