How to get the generic type used in generic IEnumerable in .net?

We have a DAL that we use with NHibernate.Search, so the classes that need to be indexed are decorated with an attribute Indexed(Index:="ClassName"), and each property that needs to be indexed has an attribute Field(Index:=Index.Tokenized, Store:=Store.No). When you need an index to expand special objects, there is an attributeIndexedEmbedded()

To automatically document our indexing hierarchy, I built a simple parser that goes through the DAL assembly, selects any class that is marked as indexable, and gets properties that are either indexable or a type that can be drilled down. When a property type is declared available for drillthrough, I click this type in the queue and process it too.

The problem is that among the classes that you can expand, some of them are in common IEnumerable collections. I would like to get the type used for the collection (usually ISet) to parse it.

So what is the way to get the internal type of the collection?

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

How do I get to ThisClasswhen I have PropertyInfoto GetToIt?

+3
source share
1 answer

Sort of:

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

(I used here IEnumerable<T>, but it is easily configurable according to any other similar interface)

+4
source

Source: https://habr.com/ru/post/1769300/


All Articles