代码之家  ›  专栏  ›  技术社区  ›  Victor

确定C中的列表类型#

  •  3
  • Victor  · 技术社区  · 14 年前

    List<MyObject> ?

    Type type = customerList.GetType();
    
    //what should I do with type here to determine if customerList is List<Customer> ?
    

    谢谢。

    2 回复  |  直到 14 年前
        1
  •  9
  •   Tim Robinson    14 年前

    List<something>

    Type type = customerList.GetType();
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        itemType = type.GetGenericArguments()[0];
    else
        // it's not a list at all
    

    编辑: List<MyObject>? ,使用 is 正常操作员:

    isListOfMyObject = customerList is List<MyObject>
    

    或者,如果你只有一个 Type :

    isListOfMyObject = typeof<List<MyObject>>.IsAssignableFrom(type)
    
        2
  •  0
  •   µBio    14 年前
    Type[] typeParameters = type.GetGenericArguments();
    if( typeParameters.Contains( typeof(Customer) ) )
    {
        // do whatever
    }