如何判断Type是列表还是数组还是IEnumerable或

时间:2010-11-07 00:46:02

标签: c# reflection

给定一个Type对象,最简单的方法是测试它是否实际上是一个对象列表?即数组或IEnumerable / IEnumerable<>。

6 个答案:

答案 0 :(得分:50)

检查typeof(IEnumerable).IsAssignableFrom(type)

每个集合类型(包括数组和IEnumerable<T>)都实现IEnumerable

答案 1 :(得分:0)

if (objType.IsArray || objType.IsGenericType)
{

}

答案 2 :(得分:0)

typeof(IEnumerable<object>).IsAssignableFrom(propertyInfo.PropertyType)

如果我们要通过通用T进行验证。

答案 3 :(得分:-1)

这不能完全回答问题,但是我认为这对那些撰写这篇文章的人来说是有用的代码。

鉴于对象 IList ,您可以使用以下代码检查对象是否为数组

IList<string> someIds = new string[0];
if (someIds is Array)
{
    // yes!
}

IList<string> someIds = new List<string>(0);
if (someIds is Array)
{
    // nop!
}

这里的区别是我们不使用任何Type对象,而是使用 actual 对象。

答案 4 :(得分:-1)

我建议使用模式匹配。 就像在这个示例方法中一样:

public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
    if (items == null)
        return true;

    if (items is T[] arr)
        return arr.Length == 0;

    return !items.Any();
}

答案 5 :(得分:-5)

简单。最简单的方法是:

IList<T> listTest = null;

try{
     listTest = ((IList<T>)yourObject);
}
catch(Exception listException)
{
    //your object doesn't support IList and is not of type List<T>
}

IEnumerable<T> enumerableTest = null;

try{
     enumerableTest = ((IEnumerable<T>)yourObject);
}
catch(Exception enumerableException)
{
     //your object doesn't suport IEnumerable<T>;
}

=============================================== ===

您也可以尝试使用不涉及多个try / catch块的内容。如果你可以避免使用它们会更好,因为每个条件实际上都是由运行时在运行时进行评估的...它是错误的代码(尽管有时它没有办法解决它)。

Type t = yourObject.GetType();

if( t is typeof(List<OjbectType>) )   //object type is string, decimal, whatever...
{
     // t is of type List<ObjectType>...
}
else if( t is typeof(IEnumerable<ObjectType>)
{
     // t is of type IEnumerable<ObjectType>...
}
else
{
    // t is some other type.
    // use reflection to find it.
}
相关问题