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

问题描述:

我们有一个与NHibernate.Search一起使用的DAL,因此需要编制索引的类使用属性Indexed(Index:="ClassName")进行修饰,每个需要被索引的属性都有一个属性Field(Index:=Index.Tokenized, Store:=Store.No)。当需要索引深入特殊对象时,有属性IndexedEmbedded()如何检索.net中泛型IEnumerable中使用的泛型类型?

为了自动记录我们的索引层次结构,我构建了一个简单的解析器,它通过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时,我有PropertyInfoGetToIt

喜欢的东西:

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>这里,但它很容易调整,以适应任何其它类似的接口)

+0

无瑕; GetgenericArguments确实是我在寻找解决方案的地方,但我不会立刻想到在接口中寻找它。谢谢 – samy 2010-10-13 09:52:50