【问题标题】:How do I get the T part of an array T[]? [duplicate]如何获得数组 T[] 的 T 部分? [复制]
【发布时间】:2015-10-13 22:03:17
【问题描述】:

在通过反射探索泛型类型(例如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。

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

【问题讨论】:

  • typeof(TArray).GetElementType()

标签: c# reflection types


【解决方案1】:

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

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

typeof(int[]).GetElementType()

给你System.Int32

还有其他类似的方法可以获取有关数组的信息 - 例如 GetArrayRankIsArray,以及用于创建任意数组的单独反射方法 MakeArrayType

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 2017-02-08
    • 2012-06-25
    • 1970-01-01
    • 2019-12-30
    • 2012-05-06
    • 1970-01-01
    相关资源
    最近更新 更多