设置具有未知类型的VBScript变量

时间:2015-01-01 11:18:19

标签: types vbscript

VBScript有两种用于设置变量

的语法

String和Integer等基元设置为

primitive_var = 3

将对象设置为

Set my_object = some_object

我有一个可以返回的函数调用。我可以检查类型如下

If VarType(f(x, y)) = vbObject Then
  Set result = f(x, y)
Else
  result = f(x, y)
End If

但是这会浪费一个函数调用。如何只需拨打一次f?

即可完成此操作

1 个答案:

答案 0 :(得分:2)

您可以使用分配给变量的Sub,使用Set for objects:

Option Explicit

' returns regexp or "pipapo" (probably a design error,
' should be two distinct functions)
Function f(x)
  If x = 1 Then
     Set f = New RegExp
  Else
     f = "pipapo"
  End If
End Function

' assigns val to var nam, using Set for objects
' ByRef to emphasize manipulation of var nam
Sub assign(ByRef nam, val)
  If IsObject(val) Then
     Set nam = Val
  Else
     nam = Val
  End If
End Sub

Dim x
assign x, f(1) : WScript.Echo TypeName(x)
assign x, f(0) : WScript.Echo TypeName(x)

输出:

cscript 27730273.vbs
IRegExp2
String

但我希望有两个不同的函数而不是一个f()。

相关问题