我们有一个与 NHibernate.Search
一起使用的 DAL,因此需要索引的类使用属性 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
当我有 GetToIt
的 PropertyInfo
时,如何到达 ThisClass
?
最佳答案
类似于:
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>
,但它很容易调整以适应任何其他类似的界面)
关于.net - 如何检索 .net 中泛型 IEnumerable 中使用的泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3922029/