获取某个对象的属性
var properties = typeof(T).GetProperties()
.Select(x => x.Name)
.ToList()
如何获取属性的名称,哪些值不是 null
?
我怎样才能得到这些?
最佳答案
为 C# 7 尝试此代码:
public static void GetProps<T>(T obj)
{
var result = typeof(T).GetProperties()
.Select(x => new { property = x.Name, value = x.GetValue(obj) })
.Where(x => x.value != null)
.ToList();
}
或者您可以为旧的 C# 版本创建一个元组
:
public static void GetProps<T>(T obj)
{
var result = typeof(T).GetProperties()
.Select(x => Tuple.Create(x.Name, x.GetValue(obj)))
.Where(x => x.Item2 != null)
.ToList();
}
关于c# - 获取不为空的属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520352/