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

tri*_*ati 12 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; }

}
Run Code Online (Sandbox Code Playgroud)

有时这个对象会让我在任何属性中都有价值

Employee emp = new Employee();
emp.FIRST_NAME= 'abc';
Run Code Online (Sandbox Code Playgroud)

剩余值为空.还行吧

但是,如何检查对象属性中的所有值何时为空

喜欢string.IsNullOrEmpty()对象?

我正在这样检查;

if(emp.FIRST_NAME == null && emp.LAST_NAME == null && emp.TYPE == null && emp.departmentList == null ...)
Run Code Online (Sandbox Code Playgroud)

Tho*_*kow 16

您可以使用Joel Harkes提出的反射,例如,我将这种可重复使用的即用型扩展方法放在一起

public static bool ArePropertiesNotNull<T>(this T obj)
{
    return typeof(T).GetProperties().All(propertyInfo => propertyInfo.GetValue(obj) != null);    
}
Run Code Online (Sandbox Code Playgroud)

然后可以这样调用

var employee = new Employee();
bool areAllPropertiesNotNull = employee.ArePropertiesNotNull();
Run Code Online (Sandbox Code Playgroud)

现在您可以检查areAllPropertiesNotNull指示所有属性是否都为空的标志.true如果所有属性都不为null,则返回,否则返回false.


这种方法的优点

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

缺点

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

在我看来,由于开发时间和代码重复在使用时减少了ArePropertiesNotNull,因此可以忽略轻微的性能开销,但YMMV.

  • 如果您更改课程并忘记更改测试方法,反思也更具有前瞻性. (2认同)
  • 所以...反射通常很慢的部分是你试图找到所有属性(或其他)的部分.如果需要做很多事情,将属性缓存到数组中会大大加快速度. (2认同)
  • `All(propertyInfo => propertyInfo.GetValue(obj)!= null)`只有******属性******时才返回true.具有所有null属性的对象将呈现与仅具有单个null属性(false)的对象相同的结果(false),这不是根据OP的描述的测试点.我假设你要么是'Any(propertyInfo => propertyInfo.GetValue(obj)!= null)`或`!全部(propertyInfo => propertyInfo.GetValue(obj)== null)`(注意第二个的反转) (2认同)

Joe*_*kes 8

您可以通过写下代码来手动检查每个属性(最佳选项)或使用反射(在此处阅读更多内容)

Employee emp = new Employee();
var props = emp.GetType().GetProperties())
foreach(var prop in props) 
{
   if(prop.GetValue(foo, null) != null) return false;
}
return true;
Run Code Online (Sandbox Code Playgroud)

这里的例子

注意int不能为null!并且它的默认值为0.因此检查prop == default(int)比它更好== null

选项3

另一种选择是实现INotifyPropertyChanged.

在更改时,将布尔字段值设置isDirty为true,并且您只需要检查此值是否为true,以了解是否已设置任何属性(即使属性设置为null).

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