从Generic Class获取ICollection类型的属性的列表
我有一个包含一些ICollection类型属性的对象
所以基本上这个类看起来像这样:
Class Employee { public ICollection Addresses {get;set;} public ICollection Performances {get; set;} }
问题是通过使用reflection获取Generic类内部的ICollection类型的属性名称。
我的通用类是
Class CRUD { public object Get() { var properties = typeof(TEntity).GetProperties().Where(m=m.GetType() == typeof(ICollection ) ... }
但它没有用。
我怎样才能在这里获得房产?
GetProperties()
返回一个PropertyInfo[]
。 然后使用m.GetType()
执行Where
。 如果我们假设您错过了>
,这是m=>m.GetType()
,那么您实际上是在说:
typeof(PropertyInfo) == typeof(ICollection)
(告诫:实际上,它可能是一个RuntimePropertyInfo
等)
你的意思可能是:
typeof(ICollection).IsAssignableFrom(m.PropertyType)
然而! 请注意ICollection
<> ICollection<>
<> ICollection
等 – 所以它甚至不那么容易。 您可能需要:
m.PropertyType.IsGenericType && m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)
确认; 这工作:
static void Main() { Foo(); } static void Foo() { var properties = typeof(TEntity).GetProperties().Where(m => m.PropertyType.IsGenericType && m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>) ).ToArray(); // ^^^ contains Addresses and Performances }
您可以使用IsGenericType
并针对typeof(ICollection<>)
检查GetGenericTypeDefinition
typeof(ICollection<>)
public object Get() { var properties = typeof (TEntity).GetProperties() .Where(m => m.PropertyType.IsGenericType && m.PropertyType.GetGenericTypeDefinition() == typeof (ICollection<>)); }