我有多个属性的类;
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.
在我看来,由于开发时间和代码重复在使用时减少了ArePropertiesNotNull,因此可以忽略轻微的性能开销,但YMMV.
您可以通过写下代码来手动检查每个属性(最佳选项)或使用反射(在此处阅读更多内容)
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
另一种选择是实现INotifyPropertyChanged.
在更改时,将布尔字段值设置isDirty为true,并且您只需要检查此值是否为true,以了解是否已设置任何属性(即使属性设置为null).
警告:此方法每个属性仍然可以为null,但仅检查是否调用了setter(更改值).
| 归档时间: |
|
| 查看次数: |
6795 次 |
| 最近记录: |