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

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

This works fine:

var expectedType = typeof(string);
object value = \"...\";
if (value.GetType().IsAssignableFrom(expectedType))
{
     ...
}
<
6条回答
  •  悲&欢浪女
    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.

提交回复
热议问题