2009-04-27 16 views
54
public bool IsList(object value) 
    { 
     Type type = value.GetType(); 
     // Check if type is a generic list of any type 
    } 

¿Cuál es la mejor manera de comprobar si el objeto dado es una lista, o se puede convertir a una lista?¿Cómo verifico si un valor dado es una lista genérica?

+0

Tal vez a encontrar respuesta desde aquí http://stackoverflow.com/questions/755200/how-do-i-detect-that-an-object -is-a-generic-collection-and -what-types-it-contiene –

Respuesta

61
if(value is IList && value.GetType().IsGenericType) { 

} 
+0

Esto no funciona - Recibo la siguiente excepción - el valor es IList \t El uso del tipo genérico 'System.Collections.Generic.IList ' requiere '1' tipos de argumentos –

+6

Debe agregar usando System.Collections; encima de tu archivo de origen. La interfaz IList que sugerí NO es la versión genérica (de ahí el segundo control) –

+1

Tiene razón. Esto funciona como un encanto. Estaba probando esto en mi ventana de vigilancia y olvidé todo sobre el espacio de nombres faltante. Me gusta más esta solución, muy simple –

1

Probablemente la mejor manera sería hacer algo como esto:

IList list = value as IList; 

if (list != null) 
{ 
    // use list in here 
} 

esto le dará la máxima flexibilidad y también permitirá trabajar con muchos tipos diferentes que implementan la interfaz IList.

+2

esto no comprueba si es una lista * genérica * como se le pidió. – Lucas

5
if(value is IList && value.GetType().GetGenericArguments().Length > 0) 
{ 

} 
+0

Creo que necesita una llamada a GetType(), p. value.GetType(). GetGenericArguments(). Length> 0 – ScottS

+0

Oops, tienes razón. Mi error. – BFree

12
bool isList = o.GetType().IsGenericType 
       && o.GetType().GetGenericTypeDefinition() == typeof(IList<>)); 
4
public bool IsList(object value) { 
    return value is IList 
     || IsGenericList(value); 
} 

public bool IsGenericList(object value) { 
    var type = value.GetType(); 
    return type.IsGenericType 
     && typeof(List<>) == type.GetGenericTypeDefinition(); 
} 
79

para ustedes que disfrutan de la utilización de métodos de extensión:

public static bool IsGenericList(this object o) 
{ 
    var oType = o.GetType(); 
    return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>))); 
} 

Así, podríamos hacer:

if(o.IsGenericList()) 
{ 
//... 
} 
+1

Para .Net Core esto necesita ser modificado ligeramente para 'devolver oType.GetTypeInfo(). IsGenericType && oType.GetGenericTypeDefinition() == typeof (List <>);' –

2

Basado en Victor La respuesta de Rodrigues , podemos idear otro método para genéricos. De hecho, la solución original se puede reducir a sólo dos líneas:

public static bool IsGenericList(this object Value) 
{ 
    var t = Value.GetType(); 
    return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>); 
} 

public static bool IsGenericList<T>(this object Value) 
{ 
    var t = Value.GetType(); 
    return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<T>); 
} 
Cuestiones relacionadas