How to check if object is an array of a certain type?

后端 未结 6 500
陌清茗
陌清茗 2020-12-05 03:56

This works fine:

var expectedType = typeof(string);
object value = \"...\";
if (value.GetType().IsAssignableFrom(expectedType))
{
     ...
}
<
6条回答
  •  攒了一身酷
    2020-12-05 04:26

    Use Type.IsArray and Type.GetElementType() to check the element type of an array.

    Type valueType = value.GetType();
    if (valueType.IsArray && expectedType.IsAssignableFrom(valueType.GetElementType())
    {
     ...
    }
    

    Beware the Type.IsAssignableFrom(). If you want to check the type for an exact match you should check for equality (typeA == typeB). If you want to check if a given type is the type itself or a subclass (or an interface) then you should use Type.IsAssignableFrom():

    typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass))
    

提交回复
热议问题