如何获取数组 T[] 的 T 部分?

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

在通过反射探索泛型类型时,例如 IEnumerable<T>,我可以通过以下方式找到 T

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

例如:

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

数组的特殊性意味着这种方法不适用于数组,因为它们本身没有通用参数。我发现实际获取数组元素类型的唯一方法是:

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

这是一个人为的、丑陋的、容易出错的 hack。

如何找到数组元素的类型?

数组早于 .NET 中的泛型,所以这并不奇怪。

这也意味着有一种特殊的反射方法可以得到你想要的:

typeof(int[]).GetElementType()

给你 System.Int32.

还有其他类似的方法来获取有关数组的信息 - 如 GetArrayRankIsArray,以及一个单独的反射方法 创建 任意数组,MakeArrayType.