检查Object是否在每个属性中都为null

时间:2018-05-02 07:00:43

标签: c# null

我有多个属性的类;

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 ...)

2 个答案:

答案 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

这种方法的优点

  • 对于支票,属性类型是否可以为空是无关紧要的。
  • 由于上述方法是通用的,您可以将它用于您想要的任何类型,而不必为您要检查的每种类型编写样板代码。
  • 如果您以后更改课程,它更具有前瞻性。 (ispiro注释)。

缺点

  • 反射可能非常慢,在这种情况下,它肯定比你目前的编写显式代码慢。使用简单缓存(由Reginald Blue提议将消除大部分开销。

在我看来,由于开发时间和代码重复在使用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

更好

选项3

另一种选择是实施INotifyPropertyChanged

在更改时将布尔字段值isDirty设置为true,而您只需要检查此值是否为true,以确定是否已设置任何属性(即使属性设置为null。

警告:此方法每个属性仍然可以为null,但只检查是否调用了setter(更改值)。