在对象中查找空白字段 - C#

kas*_*apa 4 c#

我们有一个场景,如果在源和目标之间存在实体,我们应该合并目标中的数据,即从目标列为空的基础列复制值.

我们正在使用WCF servcie调用,我们有实体对象.

如果我有一个实体可以说Staff,员工conatins的姓名等基本属性,我们有一个列表StaffAddress,StaffEmailStaffPhone.

所以我只是想知道是否有使用LINQ或任何其他机制的方法 - 我可以找到Staff对象的属性列表为null或空白?

一个基本的方法当然是手动检查一个属性为空白?

cas*_*One 5

您可以通过反射获取所有属性,然后在每个PropertyInfo实例上调用GetValue.如果为null,则返回PropertyInfo:

static IEnumerable<PropertyInfo> GetNullProperties(object obj)
{
  // Get the properties and return only the ones where GetValue
  // does not return null.
  return 
    from pi in obj.GetType().GetProperties(
      BindingFlags.Instance | BindingFlags.Public)
    where pi.GetValue(obj, null) != null
    select pi;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这将只返回类型的公共属性,而不是非公共属性.