How do I find out whether an object's type is a subclass of IEnumerable for any value type T?

前端 未结 3 756
你的背包
你的背包 2021-02-14 21:03

I need to validate an object to see whether it is null, a value type, or IEnumerable where T is a value type. So far I have:

         


        
3条回答
  •  悲&欢浪女
    2021-02-14 21:41

    (edit - added value type bits)

    You need to check all the interfaces it implements (note it could in theory implement IEnumerable for multiple T):

    foreach (Type interfaceType in obj.GetType().GetInterfaces())
    {
        if (interfaceType.IsGenericType
            && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            Type itemType = interfaceType.GetGenericArguments()[0];
            if(!itemType.IsValueType) continue;
            Console.WriteLine("IEnumerable-of-" + itemType.FullName);
        }
    }
    

提交回复
热议问题