简体   繁体   English

对于任何值类型T,如何确定对象的类型是否为IEnumerable <T>的子类?

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

I need to validate an object to see whether it is null, a value type, or IEnumerable<T> where T is a value type. 我需要验证一个对象,看它是否为null,值类型或IEnumerable<T> ,其中T是值类型。 So far I have: 到目前为止,我有:

if ((obj == null) ||
    (obj .GetType().IsValueType))
{
    valid = true;
}
else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>)))
{
     // TODO: check whether the generic parameter is a value type.
}

So I've found that the object is null, a value type, or IEnumerable<T> for some T ; 所以我发现对象为null,值类型或某些T IEnumerable<T> ; how do I check whether that T is a value type? 如何检查T是否为值类型?

(edit - added value type bits) (编辑 - 添加值类型位)

You need to check all the interfaces it implements (note it could in theory implement IEnumerable<T> for multiple T ): 你需要检查它实现的所有接口(注意它理论上可以为多个T实现IEnumerable<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);
    }
}

My generic contribution that checks if a given type (or its base classes) implements an interface of type T: 我的通用贡献,检查给定类型(或其基类)是否实现了类型为T的接口:

public static bool ImplementsInterface(this Type type, Type interfaceType)
{
    while (type != null && type != typeof(object))
    {
        if (type.GetInterfaces().Any(@interface => 
            @interface.IsGenericType
            && @interface.GetGenericTypeDefinition() == interfaceType))
        {
            return true;
        }

        type = type.BaseType;
    }

    return false;
}

你能用GetGenericArguments做些什么吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM