C# - Get the item type for a generic list

前端 未结 9 2023
小鲜肉
小鲜肉 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:50

    Here is a solution that also works with derived classes.

    Because with this class :

      public class SubList : List
      {   }
    

    If you call : subList.GetType().GetGenericArguments().Single()

    It will throws a System.InvalidOperationException

    With this method it works for derived classes :

    public Type GetListItemType(List list)
    {
      Type type = list.GetType();
      while (type != typeof(List))
        type = type.BaseType;
      return type.GetGenericArguments().Single();
    }
    
    
    var list = new List();
    var subList = new SubList();
    Console.WriteLine(GetListItemType(list)); // System.Int32
    Console.WriteLine(GetListItemType(subList)); // System.Int32
    

提交回复
热议问题