在给定Type
对象的情况下,最简单的方法是测试它是否实际上是一个对象列表?即数组或IEnumerable / IEnumerable <>。
检查typeof(IEnumerable).IsAssignableFrom(type)
。
每个集合类型,包括数组和IEnumerable<T>
,都实现了IEnumerable
。
if (objType.IsArray || objType.IsGenericType)
{
}
简单。最简单的方法是:
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.
}