我的一个脚本不断出现此错误:
对象不是集合
因此,我想创建一个函数,在对该对象执行任何操作之前检查该对象是否为集合。
到目前为止,我已经创建了这个:
Function IsCollection(param)
If IsEmpty(param) Then
IsCollection = False
ElseIf(TypeName(param) = "String") Then
IsCollection = False
Else
IsCollection = True
End If
End Function
但我得到我错过了一些检查的感觉-当然唯一可用的类型不只是String
,Empty
还是Collection
?
我认为尝试枚举可能会更好param
,如果这会返回错误,那么我知道要输出false
-这似乎是更好的选择吗?
Function IsCollection(param)
For Each p In param
' Anything need to go here?
Next
If Err > 0 Then
IsCollection = False
Else
IsCollection = True
End If
End Function
即使在第二个示例中,指定给出的错误是否为“对象不是集合”是否明智?
VBScript并不真正支持类型自省。你可以检查TypeName
的param
,但随后你需要实现一个枚举接口的所有类的权威列表。
我想说的最好的选择确实是尝试枚举param
并检查是否出现运行时错误451:
Function IsCollection(param)
On Error Resume Next
For Each p In param
Exit For
Next
If Err Then
If Err.Number = 451 Then
IsCollection = False
Else
WScript.Echo "Unexpected error (0x" & Hex(Err.Number) & "): " & _
Err.Description
WScript.Quit 1
End If
Else
IsCollection = True
End If
End Function
确保您On Error Resume Next
尽可能保留本地化的范围,最好在此函数内部使用它。
正如Tomalak在评论中提到的那样,以上内容不仅将“常规”集合报告为集合,而且还将VBScript内置数组作为报告(因为它们也是可枚举的)。为了避免这种改变线
IsCollection = True
至
IsCollection = Not IsArray(param)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句