我有多个属性的类;
public class Employee
{
public string TYPE { get; set; }
public int? SOURCE_ID { get; set; }
public string FIRST_NAME { get; set; }
public string LAST_NAME { get; set; }
public List<Department> departmentList { get; set; }
public List<Address> addressList { get; set; }
}
有时这个对象会在任何属性中返回我的值
Employee emp = new Employee();
emp.FIRST_NAME= 'abc';
其余值为null。这没关系
但是,如何检查对象属性中的所有值是否为空
对象是string.IsNullOrEmpty()
吗?
目前我正在检查这个;
if(emp.FIRST_NAME == null && emp.LAST_NAME == null && emp.TYPE == null && emp.departmentList == null ...)
答案 0 :(得分:13)
您可以使用Joel Harkes建议的反射,例如我将这种可重用的,可立即使用的扩展方法放在一起
public static bool ArePropertiesNotNull<T>(this T obj)
{
return typeof(T).GetProperties().All(propertyInfo => propertyInfo.GetValue(obj) != null);
}
然后可以像这样调用
var employee = new Employee();
bool areAllPropertiesNotNull = employee.ArePropertiesNotNull();
现在您可以检查areAllPropertiesNotNull
标志,该标志指示是否所有属性都不为空。如果所有属性都不为null,则返回true
,否则返回false
。
在我看来,由于开发时间和代码重复在使用ArePropertiesNotNull
但YMMV时减少了,因此可以忽略轻微的性能开销。
答案 1 :(得分:8)
要么通过写下代码来手动检查每个属性(最佳选项),要么使用反射(阅读更多here)
Employee emp = new Employee();
var props = emp.GetType().GetProperties())
foreach(var prop in props)
{
if(prop.GetValue(foo, null) != null) return false;
}
return true;
来自here
的示例注意int不能为null!并且其默认值为0.因此,检查prop == default(int)
比== null
另一种选择是实施INotifyPropertyChanged。
在更改时将布尔字段值isDirty
设置为true,而您只需要检查此值是否为true,以确定是否已设置任何属性(即使属性设置为null。
警告:此方法每个属性仍然可以为null,但只检查是否调用了setter(更改值)。