mardi 13 octobre 2015

How do I get the T part of an array T[]?

When exploring, through Reflection, a generic type such as IEnumerable<T>, I can find T by doing:

public Type Demo<TSequence>()
{
    return typeof(TSequence).GenericTypeArguments[0];
}

For instance:

typeof(Collection<short>).GenericTypeArguments[0].FullName == "System.Int16"

The specifics of arrays means that this approach doesn't work for arrays, since they don't have generic parameters per se. The only way I've found to actually get the type of the element of an array is to do:

public Type Demo<TArray>()
{
    return typeof(TArray)
        .GetTypeInfo()
        .DeclaredMethods
        .Single(m => m.Name == "Get")
        .ReturnType;
}

which is a contrived, ugly and error prone hack.

How do I find the type of elements of an array?





Aucun commentaire:

Enregistrer un commentaire