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

标签 .net reflection types ienumerable

我们有一个与 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

当我有 GetToItPropertyInfo 时,如何到达 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/

相关文章:

.net - 如何在 WiX 中指定所需的最低 .NET 框架版本

c# - 有没有混淆C#源代码的程序?

types - 在 Ocaml 中重用和扩展定义的类型

types - Agda:形成所有对 {(x , y) | x 在 xs,y 在 ys}

python - 为什么在 Python 中从不同路径调用类时 __class__ 不同?

.NET应用Mysql远程数据库同步

c# - 如何在大括号内不使用字符串连接的情况下使用字符串格式作为参数?

c# - "Method is not declared within generic type definition"错误

java - java.lang.reflect.Proxy 实例是否经过特殊处理以进行终结?

c# - 实例化一个内部类并将其转换为给定类型