C# - Get the item type for a generic list

前端 未结 9 1980
小鲜肉
小鲜肉 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 07:01
    list.GetType().GetGenericArguments()[0]
    
    0 讨论(0)
  • 2020-12-05 07:05

    You could use the Type.GetGenericArguments method for this purpose.

    List<Foo> myList = ...
    
    Type myListElementType = myList.GetType().GetGenericArguments().Single();
    
    0 讨论(0)
  • 2020-12-05 07:07
    Public Shared Function ListItemType(ListType As System.Type) As System.Type
    
      If Not ListType.IsGenericType Then
        If ListType.BaseType IsNot Nothing AndAlso ListType.BaseType.IsGenericType Then
          Return ListItemType(ListType.BaseType)
        End If
      Else
        Return ListType.GetGenericArguments.Single
      End If
    End Function
    
    0 讨论(0)
提交回复
热议问题