简体   繁体   中英

Get contained type in a List<T> through reflection?

Through reflection, is there some way for me to look at a generic List's contained type to see what type the collection is of? For example:

I have a simple set of business objects that derive from an interface, like this:

public interface IEntityBase{}  

public class BusinessEntity : IEntityBase   
{
    public IList<string> SomeStrings {get; set;}       
    public IList<ChildBusinessEntity> ChildEntities { get; set;}
} 

public class ChildBusinessEntity : IEntityBase{}

In the case where I am iterating through the properties of BusinessEntity through reflection, would there be a way for me to see if the objects nested inside those lists derived from IEntityBase?

Pseudo coded (badly) like this:

foreach(PropertyInfo info in typeof(BusinessEntity).GetProperties())
{
  if(info.PropertyType is GenericIList &&
     TheNestedTypeInThisList.IsAssignableFrom(IEntityBase)
  {
    return true;
  }
}

Only option I've heard so far, that works, would be to pull out the first item from that list, then look at its type. Any easier way (especially because I can't be guaranteed that the List won't be empty)?

假设您有描述List<>System.Type ,您可以使用Type.GetGenericArguments()方法获取Type实例,该实例描述了它的列表。

something like this?

foreach (System.Reflection.PropertyInfo info 
                                       in typeof(BusinessEntity).GetProperties())
{
    if (info.PropertyType.IsGenericType &&
        info.PropertyType.Name.StartsWith("IList") &&
        info.PropertyType.GetGenericArguments().Length > 0 &&
        info.PropertyType.GetGenericArguments()[0] == typeof(string)
        )
    {
        return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM