C# 通过反射获取 List<T> 中包含的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/538111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:17:22  来源:igfitidea点击:

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

c#.netgenericsreflection

提问by joshua.ewer

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:

通过反射,是否有某种方法可以让我查看泛型 List 的包含类型以查看集合的类型?例如:

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?

在我通过反射遍历 BusinessEntity 属性的情况下,有没有办法让我查看嵌套在这些列表中的对象是否从 IEntityBase 派生?

Pseudocoded (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 不会为空)?

采纳答案by ChrisW

Assuming you have the System.Typewhich describes your List<>, you can use the Type.GetGenericArguments()method to get the Typeinstance which describes what it's a list of.

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

回答by Avram

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;
    }
}