Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何确定对象';s type是IEnumerable的一个子类<;T>;对于任何值类型T?_C#_.net_Generics_Reflection - Fatal编程技术网

C# 如何确定对象';s type是IEnumerable的一个子类<;T>;对于任何值类型T?

C# 如何确定对象';s type是IEnumerable的一个子类<;T>;对于任何值类型T?,c#,.net,generics,reflection,C#,.net,Generics,Reflection,我需要验证一个对象,看看它是null、值类型还是IEnumerable,其中T是值类型。到目前为止,我已经: if ((obj == null) || (obj .GetType().IsValueType)) { valid = true; } else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>))) { // TODO: check whether the generic parameter

我需要验证一个对象,看看它是null、值类型还是
IEnumerable
,其中
T
是值类型。到目前为止,我已经:

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.
}
if((obj==null)||
(obj.GetType().IsValueType))
{
有效=真;
}
else if(obj.GetType().IsSubclassOf(typeof(IEnumerable)))
{
//TODO:检查泛型参数是否为值类型。
}
所以我发现这个对象是null,一个值类型,或者对于某些
T
,它是
IEnumerable
;如何检查
T
是否为值类型?

(编辑-增值类型位)

您需要检查它实现的所有接口(注意,对于多个
T
,理论上它可以实现
IEnumerable
):

foreach(在obj.GetType().GetInterfaces()中键入interfaceType)
{
if(interfaceType.IsGenericType
&&interfaceType.GetGenericTypeDefinition()==typeof(IEnumerable))
{
类型itemType=interfaceType.GetGenericArguments()[0];
如果(!itemType.IsValueType)继续;
WriteLine(“IEnumerable of-”+itemType.FullName);
}
}

你能用
GetGenericaArguments
做点什么吗?

我的泛型贡献,检查给定类型(或其基类)是否实现了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;
}

GetInterfaces是否具有足够的递归性,意味着您不需要担心父类型的上升?您不需要递归。类要么实现接口,要么不实现接口。这是一个简单的列表,不管接口本身如何“继承”彼此。
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;
}