Подтвердить что ты не робот

Как определить, является ли тип списком или массивом, или IEnumerable или

Какой самый простой способ, с учетом объекта Type, проверить, действительно ли это список объектов? То есть Массив или IEnumerable/IEnumerable < > .

4b9b3361

Ответ 1

Проверьте typeof(IEnumerable).IsAssignableFrom(type).

Каждый тип коллекции, включая массивы и IEnumerable<T>, реализует IEnumerable.

Ответ 2

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

}

Ответ 3

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

Если мы проверяем от Generic T.

Ответ 4

Simple. Проще всего сделать следующее:

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.
}