.NET Reflection: Detecting IEnumerable

后端 未结 3 1362
南旧
南旧 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 10:55

    Note that you cannot call GetGenericTypeDefinition() on a non-generic type, therefore, first check with IsGenericType.

    I'm not sure if you want to check whether a type implements a generic IEnumerable<> or if you want to see if an interface type is IEnumerable<>. For the first case, use the following code (the inner check with interfaceType is the second case):

    if (typeof(IEnumerable).IsAssignableFrom(type)) {
        foreach (Type interfaceType in type.GetInterfaces()) {
            if (interfaceType.IsGenericType && (interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))) {
                Console.WriteLine("{0} implements {1} enumerator", type.FullName, interfaceType.FullName); // is a match
            }
        }
    }
    

提交回复
热议问题