如何获取非集合属性的属性
本文关键字:属性 集合 获取 何获取 | 更新日期: 2024-09-21 14:59:28
我有一个继承EntityBase
:的Person
类
public class Person : EntityBase
{
virtual public string FirstName { get; set; }
virtual public string LastName { get; set; }
virtual public IList<Asset> Assets { get; set; }
}
和
public class EntityBase : IEntity
{
public virtual long Id { get; protected set; }
public virtual IEnumurable<string> Errors { get; protected set; }
}
我需要获得不是集合的Person
类的属性列表
现在GetProperties()
包括:FirstName, LastName, Assets, Id, Errors
,但我只需要不需要数组属性:FirstName, LastName, Id
如何获取非集合的属性?
您可以根据属性的返回类型进行筛选。我怀疑您想过滤掉任何实现IEnumerable
的内容,但不是string
(它实现了IEnumerable<char>
,但您想保留它)。所以类似于:
var properties = type.GetProperties()
.Where(p => p.PropertyType == typeof(string) ||
!typeof(IEnumerable).IsAssignableFrom(p.PropertyType));