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

问题描述 投票:32回答:3

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

c# reflection
3个回答
50
投票

检查typeof(IEnumerable).IsAssignableFrom(type)

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


0
投票
if (objType.IsArray || objType.IsGenericType)
{

}

-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.
}
© www.soinside.com 2019 - 2024. All rights reserved.