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 si se puede convertir en una lista?
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 si se puede convertir en una lista?
Respuestas:
using System.Collections; if(value is IList && value.GetType().IsGenericType) { }fuente
List<T>y seObservableCollection<T>implementaIList.Para ustedes que disfrutan del uso de métodos de extensión:
public static bool IsGenericList(this object o) { var oType = o.GetType(); return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>))); }Entonces, podríamos hacer:
if(o.IsGenericList()) { //... }fuente
return oType.GetTypeInfo().IsGenericType && oType.GetGenericTypeDefinition() == typeof(List<>);IList<>Sería más seguro buscar en su lugar?bool isList = o.GetType().IsGenericType && o.GetType().GetGenericTypeDefinition() == typeof(IList<>));fuente
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(); }fuente
if(value is IList && value.GetType().GetGenericArguments().Length > 0) { }fuente
Según la respuesta de Victor Rodrigues, podemos idear otro método para los genéricos. De hecho, la solución original se puede reducir a solo 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>); }fuente
Aquí hay una implementación que funciona en .NET Standard y funciona con interfaces:
public static bool ImplementsGenericInterface(this Type type, Type interfaceType) { return type .GetTypeInfo() .ImplementedInterfaces .Any(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == interfaceType); }Y aquí están las pruebas (xunit):
[Fact] public void ImplementsGenericInterface_List_IsValidInterfaceTypes() { var list = new List<string>(); Assert.True(list.GetType().ImplementsGenericInterface(typeof(IList<>))); Assert.True(list.GetType().ImplementsGenericInterface(typeof(IEnumerable<>))); Assert.True(list.GetType().ImplementsGenericInterface(typeof(IReadOnlyList<>))); } [Fact] public void ImplementsGenericInterface_List_IsNotInvalidInterfaceTypes() { var list = new List<string>(); Assert.False(list.GetType().ImplementsGenericInterface(typeof(string))); Assert.False(list.GetType().ImplementsGenericInterface(typeof(IDictionary<,>))); Assert.False(list.GetType().ImplementsGenericInterface(typeof(IComparable<>))); Assert.False(list.GetType().ImplementsGenericInterface(typeof(DateTime))); }fuente
Estoy usando el siguiente código:
public bool IsList(Type type) => IsGeneric(type) && ( (type.GetGenericTypeDefinition() == typeof(List<>)) || (type.GetGenericTypeDefinition() == typeof(IList<>)) );fuente
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 le permitirá trabajar con muchos tipos diferentes que implementan la
IListinterfaz.fuente