且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否目的是某一类型的数组?

更新时间:2023-11-28 22:20:40

使用类型。 IsArray的和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())
{
 ...
}

当心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))