首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从.net中的数组类型获取数组项类型

如何从.net中的数组类型获取数组项类型
EN

Stack Overflow用户
提问于 2010-11-09 09:54:41
回答 2查看 24.4K关注 0票数 75

假设我有一个System.String[]类型的对象。我可以查询类型对象来确定它是否是数组

代码语言:javascript
复制
Type t1 = typeof(System.String[]);
bool isAnArray = t1.IsArray; // should be true

但是,如何从t1获取数组项的类型对象

代码语言:javascript
复制
Type t2 = ....; // should be typeof(System.String)
EN

回答 2

Stack Overflow用户

发布于 2014-02-25 02:21:15

感谢@psaxton数组指出了comment和其他集合之间的区别。作为扩展方法:

代码语言:javascript
复制
public static class TypeHelperExtensions
{
    /// <summary>
    /// If the given <paramref name="type"/> is an array or some other collection
    /// comprised of 0 or more instances of a "subtype", get that type
    /// </summary>
    /// <param name="type">the source type</param>
    /// <returns></returns>
    public static Type GetEnumeratedType(this Type type)
    {
        // provided by Array
        var elType = type.GetElementType();
        if (null != elType) return elType;

        // otherwise provided by collection
        var elTypes = type.GetGenericArguments();
        if (elTypes.Length > 0) return elTypes[0];

        // otherwise is not an 'enumerated' type
        return null;
    }
}

用法:

代码语言:javascript
复制
typeof(Foo).GetEnumeratedType(); // null
typeof(Foo[]).GetEnumeratedType(); // Foo
typeof(List<Foo>).GetEnumeratedType(); // Foo
typeof(ICollection<Foo>).GetEnumeratedType(); // Foo
typeof(IEnumerable<Foo>).GetEnumeratedType(); // Foo

// some other oddities
typeof(HashSet<Foo>).GetEnumeratedType(); // Foo
typeof(Queue<Foo>).GetEnumeratedType(); // Foo
typeof(Stack<Foo>).GetEnumeratedType(); // Foo
typeof(Dictionary<int, Foo>).GetEnumeratedType(); // int
typeof(Dictionary<Foo, int>).GetEnumeratedType(); // Foo, seems to work against key
票数 13
EN

Stack Overflow用户

发布于 2017-05-07 08:02:15

感谢@drzaus的漂亮answer,但它可以被压缩成一个线条(加上对nullIEnumerable类型的检查):

代码语言:javascript
复制
public static Type GetEnumeratedType(this Type type) =>
   type?.GetElementType()
   ?? typeof(IEnumerable).IsAssignableFrom(type)
   ? type.GenericTypeArguments.FirstOrDefault()
   : null;

添加了null检查器以避免异常,也许我不应该这样做(请随意删除Null Conditional Operators)。还添加了一个筛选器,以便该函数仅适用于集合,而不适用于任何泛型类型。

请记住,这也可能被实现的子类所欺骗,这些子类更改了集合的主题,而实现者决定将集合的泛型参数移到后面的位置。

C#8和可空性的转换答案:

代码语言:javascript
复制
public static Type GetEnumeratedType(this Type type) => 
        ((type?.GetElementType() ?? (typeof(IEnumerable).IsAssignableFrom(type)
            ? type.GenericTypeArguments.FirstOrDefault()
            : null))!;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4129831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档