.NET Reflection: Detecting IEnumerable

后端 未结 3 1360
南旧
南旧 2021-01-04 10:27

I\'m trying to detect if a particular instance of a Type object is a generic \"IEnumerable\"...

The best I can come up with is:

// theType might be t         


        
3条回答
  •  清酒与你
    2021-01-04 11:03

    You can use this piece of code to determine if a particular type implements the IEnumerable interface.

    Type type = typeof(ICollection);
    
    bool isEnumerable = type.GetInterfaces()       // Get all interfaces.
        .Where(i => i.IsGenericType)               // Filter to only generic.
        .Select(i => i.GetGenericTypeDefinition()) // Get their generic def.
        .Where(i => i == typeof(IEnumerable<>))    // Get those which match.
        .Count() > 0;
    

    It will work for any interface, however it will not work if the type you pass in is IEnumerable.

    You should be able to modify it to check the type arguments passed to each interface.

提交回复
热议问题