gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:59:24 25 4
gpt4 key购买 nike

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

我们正在使用 WCF 服务调用并且我们有实体对象。

如果我有一个实体让我们说 Staff,staff 包含姓名等基本属性,我们有一个列表 StaffAddressStaffEmailStaffPhone

所以我只是想知道有没有一种方法可以使用 LINQ 或任何其他机制 - 我可以找出 Staff 对象上的属性列表,这些属性是 null 还是空白?

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

最佳答案

您可以通过反射获取所有属性,然后在每个 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;
}

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

关于c# - 查找对象中的空白字段 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/522468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com