如何检查是否目的是某一类型的数组? [英] How to check if object is an array of a certain type?
问题描述
这工作得很好:
var expectedType = typeof(string);
object value = "...";
if (value.GetType().IsAssignableFrom(expectedType))
{
...
}
但我怎么检查,如果值是一个字符串数组没有设置 expectedType
到 typeof运算(字符串[])
?我想做的事情是这样的:
But how do I check if value is a string array without setting expectedType
to typeof(string[])
? I want to do something like:
var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType().IsArrayOf(expectedType)) // <---
{
...
}
这可能吗?
推荐答案
使用类型。 IsArray的和<一href="http://msdn.microsoft.com/en-us/library/system.type.getelementtype.aspx">Type.GetElementType()检查数组的元素类型。
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())
{
...
}
当心<一href="http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx">Type.IsAssignableFrom().如果你想查询的类型完全匹配,你应该检查是否相等(的typeA == TYPEB
)。如果要检查是否给定的类型是类型本身或子类(或接口),那么你应该使用 Type.IsAssignableFrom()
:
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))
这篇关于如何检查是否目的是某一类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!