How do I get the Array Item Type from Array Type in .net

后端 未结 3 1379
清酒与你
清酒与你 2020-12-09 00:54

Say I have an System.String[] type object. I can query the type object to determine if it is an array

Type t1 = typeof(System.String[]);
bool i         


        
3条回答
  •  一个人的身影
    2020-12-09 01:04

    Thanks to @psaxton comment pointing out the difference between Array and other collections. As an extension method:

    public static class TypeHelperExtensions
    {
        /// 
        /// If the given  is an array or some other collection
        /// comprised of 0 or more instances of a "subtype", get that type
        /// 
        /// the source type
        /// 
        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;
        }
    }
    

    Usage:

    typeof(Foo).GetEnumeratedType(); // null
    typeof(Foo[]).GetEnumeratedType(); // Foo
    typeof(List).GetEnumeratedType(); // Foo
    typeof(ICollection).GetEnumeratedType(); // Foo
    typeof(IEnumerable).GetEnumeratedType(); // Foo
    
    // some other oddities
    typeof(HashSet).GetEnumeratedType(); // Foo
    typeof(Queue).GetEnumeratedType(); // Foo
    typeof(Stack).GetEnumeratedType(); // Foo
    typeof(Dictionary).GetEnumeratedType(); // int
    typeof(Dictionary).GetEnumeratedType(); // Foo, seems to work against key
    

提交回复
热议问题