代码之家  ›  专栏  ›  技术社区  ›  samy

如何检索.NET中泛型IEnumerable中使用的泛型类型?

  •  3
  • samy  · 技术社区  · 14 年前

    我们用的是DAL NHibernate.Search ,因此需要索引的类用属性修饰。 Indexed(Index:="ClassName") ,并且需要索引的每个属性都有一个属性 Field(Index:=Index.Tokenized, Store:=Store.No) . 当人们希望索引向下钻取特殊对象时,有一个属性 IndexedEmbedded()

    为了自动记录我们的索引层次结构,我构建了一个简单的解析器,它运行在DAL程序集中,获取标记为可索引的任何类,并获取可索引的属性或其类型可用于向下钻取的属性。当属性的类型声明为可用于向下钻取时,我将此类型推入队列并对其进行处理。

    问题是,在您可以向下钻取的类中,有些类本身包含在IEnumerable泛型集合中。我想得到用于集合(通常是ISET)的类型来解析它。

    那么,如何获得集合的内部类型呢?

    Private m_TheMysteriousList As ISet(Of ThisClass)
    <IndexedEmbedded()> _
    Public Overridable Property GetToIt() As ISet(Of ThisClass)
       Get
            Return m_TheMysteriousList
       End Get
       Set(ByVal value As ISet(Of ThisClass))
            m_TheMysteriousList = value
       End Set
    End Property
    

    我怎样才能到达 ThisClass 当我拥有 PropertyInfo 对于 GetToIt ?

    1 回复  |  直到 14 年前
        1
  •  4
  •   Marc Gravell    14 年前

    类似:

    public static Type GetEnumerableType(Type type)
    {
        if (type == null) throw new ArgumentNullException();
        foreach (Type interfaceType in type.GetInterfaces())
        {
            if (interfaceType.IsGenericType &&
                interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                return interfaceType.GetGenericArguments()[0];
            }
        }
        return null;
    }
    ...
    PropertyInfo prop = ...
    Type enumerableType = GetEnumerableType(prop.PropertyType);
    

    (我已经用过了 IEnumerable<T> 这里,但它很容易调整以适应任何其他类似的接口)