【问题标题】:Can a VBScript function return a dictionary?VBScript 函数可以返回字典吗?
【发布时间】:2010-10-27 21:58:37
【问题描述】:
我有一个表格数据字典,我想使用函数进行修改。
function queryCleanForm(myDictForm)
dim arrayKeys
arrayKeys = myDictForm.keys
for i=0 to myDictForm.count-1
myDictForm(arrayKeys(i)) = replace(myDictForm(arrayKeys(i)), "'", "''")
response.write myDictForm(arrayKeys(i))
next
queryCleanForm = myDictForm
end function
问题是queryCleanForm = myDictForm 行错误为
Wrong number of arguments or invalid property assignment
有没有办法在 VBScript 中做到这一点?
【问题讨论】:
标签:
asp-classic
dictionary
vbscript
【解决方案1】:
试试这个:
SET queryCleanForm = myDictForm
对于对象,您需要使用 SET 来告诉 VBScript 这是您分配的对象引用而不是值类型。
【解决方案2】:
是的,你需要使用 SET 命令:
设置 queryCleanForm = myDictForm
【解决方案3】:
您还可以在函数中使用 ByRef 或 ByVal 值。 ByVal,您发送给函数或子的对象被复制到私有内存中以在函数内部使用并在函数完成后丢弃。 ByRef,您发送给函数的对象被引用,您所做的所有操作,删除键,设置对象等,都直接对您发送的对象进行。
例如
Sub test
DIM testDict as variant
call setdict(testDict)
testDict.Add "test", "value"
call addValue(testDict, "test2","another value")
msgbox testDict.Count
Set testDict = Nothing
End Sub
Sub setdict(ByRef in_Dict as Variant)
If Typename(in_Dict) <> "Dictionary" Then
SET in_Dict = CreateObject("Scripting.Dictionary")
end if
end sub
sub addValue(ByRef in_Obj as Variant, ByVal in_Key as String, ByVal in_Value as String)
if not in_Obj.Exists(in_Key) then
in_Obj.Add in_Key, in_Value
end if
end sub
测试子用一个variant类型的变量调用子setdict。在函数中,我验证发送到子对象的类型。如果对象类型不是字典对象(它不是),那么实际上是子测试中声明的 testDict 对象的 in_Dict 对象将被设置为字典对象。
为了更好地演示参考,我还包括了第二个子组件,称为 addvalue。我再次将对象作为引用传递给函数,并向字典对象添加另一个键。在主要测试子生病然后发布计数。在这种情况下,存在 2 个键。