How to determine if a type is a type of collection?

前端 未结 3 1781
无人共我
无人共我 2021-02-03 17:50

I am trying to determine if a runtime type is some sort of collection type. What I have below works, but it seems strange that I have to name the types that I believe to be coll

相关标签:
3条回答
  • 2021-02-03 18:21

    Really all of these types inherit IEnumerable. You can check only for it:

    bool IsEnumerableType(Type type)
    {
        return (type.GetInterface(nameof(IEnumerable)) != null);
    }
    

    or if you really need to check for ICollection:

    bool IsCollectionType(Type type)
    {
        return (type.GetInterface(nameof(ICollection)) != null);
    }
    

    Look at "Syntax" part:

    • List<T>

    • IList

    • ICollection

    0 讨论(0)
  • 2021-02-03 18:22

    You can use linq, search for an interface name like

    yourobject.GetType().GetInterfaces().Where(s => s.Name == "IEnumerable")
    

    If this has values is a instance of IEnumerable.

    0 讨论(0)
  • 2021-02-03 18:30

    You can use this helper method to check if a type implements an open generic interface. In your case you can use DoesTypeSupportInterface(type, typeof(Collection<>))

    public static bool DoesTypeSupportInterface(Type type,Type inter)
    {
        if(inter.IsAssignableFrom(type))
            return true;
        if(type.GetInterfaces().Any(i=>i. IsGenericType && i.GetGenericTypeDefinition()==inter))
            return true;
        return false;
    }
    

    Or you can simply check for the non generic IEnumerable. All collection interfaces inherit from it. But I wouldn't call any type that implements IEnumerable a collection.

    0 讨论(0)
提交回复
热议问题