【问题标题】:Get contained type in a List<T> through reflection?通过反射获取 List<T> 中包含的类型?
【发布时间】:2009-02-11 18:24:05
【问题描述】:

通过反思,有什么方法可以让我查看泛型 List 的包含类型以了解集合的类型?例如:

我有一组从接口派生的简单业务对象,如下所示:

public interface IEntityBase{}  

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

public class ChildBusinessEntity : IEntityBase{}

如果我通过反射遍历 BusinessEntity 的属性,是否有办法查看嵌套在从 IEntityBase 派生的那些列表中的对象?

编码(糟糕)如下:

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

到目前为止,我听到的唯一可行的方法是从该列表中拉出第一项,然后查看其类型。任何更简单的方法(特别是因为我不能保证列表不会为空)?

【问题讨论】:

  • 不是骗子:这个问题是在询问嵌套类型,而这个问题(尽管有标题)似乎是在询问泛型类型。
  • 哎呀,你是对的,我的错:P
  • 我在这里看不到任何嵌套类型;你应该改变标题。
  • 我的错。我称它为“嵌套”是因为我不知道还能叫它什么,直到我意识到它有不同的内涵。标题已更改。不管怎样,ChrisW 找到了我要找的东西。回想起来也有道理……

标签: c# .net generics reflection


【解决方案1】:

假设您有描述您的List&lt;&gt;System.Type,您可以使用Type.GetGenericArguments() 方法获取描述其列表内容的Type 实例。

【讨论】:

    【解决方案2】:

    类似的东西?

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

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 2010-12-26
      • 1970-01-01
      • 2016-07-06
      • 2016-08-24
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多