Csharp/C#教程:从Generic Class获取ICollection类型的属性的列表分享


从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<>)

上述就是C#学习教程:从Generic Class获取ICollection类型的属性的列表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public object Get() { var properties = typeof (TEntity).GetProperties() .Where(m => m.PropertyType.IsGenericType && m.PropertyType.GetGenericTypeDefinition() == typeof (ICollection<>)); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/943537.html

(0)
上一篇 2021年11月14日
下一篇 2021年11月14日

精彩推荐