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

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

This works fine:

var expectedType = typeof(string);
object value = \"...\";
if (value.GetType().IsAssignableFrom(expectedType))
{
     ...
}
<
相关标签:
6条回答
  • 2020-12-05 04:12

    The neatest and securest way to do it that found is using MakeArrayType:

    var expectedType = typeof(string);
    object value = new[] {"...", "---"};
    if (value.GetType() == expectedType.MakeArrayType())
    {
         ...
    }
    
    0 讨论(0)
  • 2020-12-05 04:13
    value.GetType().GetElementType() == typeof(string)
    

    as an added bonus (but I'm not 100% sure. This is the code I use...)

    var ienum = value.GetType().GetInterface("IEnumerable`1");
    
    if (ienum != null) {
        var baseTypeForIEnum = ienum.GetGenericArguments()[0]
    }
    

    with this you can look for List, IEnumerable... and get the T.

    0 讨论(0)
  • 2020-12-05 04:17

    Do you actually need to know the type of the array? Or do you only need the elements to be of a certain type?

    If the latter, you can simply filter only the elements that match what you want:

    string[] strings = array.OfType<string>();
    
    0 讨论(0)
  • 2020-12-05 04:22
    if(objVal.GetType().Name == "Object[]")
    

    true for array

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-12-05 04:28

    You can use extension methods (not that you have to but makes it more readable):

    public static class TypeExtensions
    {
        public static bool IsArrayOf<T>(this Type type)
        {
             return type == typeof (T[]);
        }
    } 
    

    And then use:

    Console.WriteLine(new string[0].GetType().IsArrayOf<string>());
    
    0 讨论(0)
提交回复
热议问题