C# - Get the item type for a generic list

前端 未结 9 2037
小鲜肉
小鲜肉 2020-12-05 06:15

What would be the best way of getting the type of items a generic list contains? It\'s easy enough to grab the first item in the collection and call .GetType(), but I can\'

9条回答
  •  孤城傲影
    2020-12-05 06:58

    Here's another way which works for non-generic collections, too:

    static Type GetItemType(Type collectionType)
    {
        return collectionType.GetMethod("get_Item").ReturnType;
    }
    

    That is, get the return type of foo[x], where foo is of the specified type.

    Examples:

    // Generic type; prints System.Int32
    Console.WriteLine(GetItemType(typeof(List)));
    
    // Non-generic type; prints System.String
    Console.WriteLine(GetItemType(typeof(System.Collections.Specialized.StringCollection)));
    

    The GetItemType method above has a couple issues, though:

    • It throws a NullReferenceException if the type has no indexing operator.

    • It throws an AmbiguousMatchException if the type has multiple overloads for the indexing operator (e.g. this[string] and this[int]).

    Here is a more refined version:

    public static Type GetItemType(this Type collectionType)
    {
        var types =
            (from method in collectionType.GetMethods()
             where method.Name == "get_Item"
             select method.ReturnType
            ).Distinct().ToArray();
        if (types.Length == 0)
            return null;
        if (types.Length != 1)
            throw new Exception(string.Format("{0} has multiple item types", collectionType.FullName));
        return types[0];
    }
    

提交回复
热议问题