开发者

How to tell whether a Type is a list or array or IEnumerable or

What's the easiest way, given a Type object, to test to see whether it is actually a list of objects? I.开发者_如何学Pythone. Array or IEnumerable/IEnumerable<>.


Check typeof(IEnumerable).IsAssignableFrom(type).

Every collection type, including arrays and IEnumerable<T>, implements IEnumerable.


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

}


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

If we are verifying from Generic T.


This does not exactly answers the question but I think this is a helpful code for those who landed on this post.

Given an object or an IList<T>, you can use the following code to check whether the object is an array.

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

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

The difference here is that we are not working with any Type object but on the actual objects.


I would recommend using pattern matching. Like in this sample method:

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();
}


Simple. The easiest thing to do is the following:

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

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

You can also try this which doesn't involve multiple try/catch blocks. It's better if you can avoid using those because each condition is actually evaluated by the runtime during runtime... it's bad code (though sometimes there's no way around it).

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜