如何通过字符串变量引用对象?除了使用执行和丢失选项显式
之外,我觉得除此之外还有办法做到这一点示例(其中“有问题的命令/方法”:
Dim strObj
Dim D1 : Set D1 = CreateObject("Scripting.Dictionary")
strObj = "D1"
Something(strObj).add "1" , "Car"
msgbox Something(strObj).Item("1")
谢谢!
答案 0 :(得分:1)
functions
只能引用subs
(和Set functionReference = GetRef("myFunction")
),但不能引用对象。
当您想要一个字符串引用时,您必须为每个要引用的对象创建一个。您可以使用字典:
Dim foo, bar
Dim StringObjectReference : Set StringObjectReference = CreateObject("Scripting.Dictionary")
' Lets create some objects
Set foo = CreateObject("System.Collections.ArrayList")
Set bar = CreateObject("Scripting.Dictionary")
' Register the objects for referral, now we can reference them by string!
StringObjectReference.Add "foo", foo
StringObjectReference.Add "bar", bar
' Manipulate the objects through their string reference
StringObjectReference("foo").Add "BMW"
StringObjectReference("foo").Add "Chrysler"
StringObjectReference("foo").Add "Audi"
StringObjectReference("foo").Sort
StringObjectReference("bar").Add "Bikes", array("Honda", "Thriumph")
StringObjectReference("bar").Add "Quads", array("Honda", "Kawasaki", "BMW")
' Retrieve values from the objects
' real:
msgbox "My Cars: " & join(foo.ToArray(), ", ")
msgbox "My Bikes: " & join(bar("Bikes"), ", ")
msgbox "My Quads: " & join(bar("Quads"), ", ")
' From reference
msgbox "My Cars: " & join(StringObjectReference("foo").ToArray(), ", ")
msgbox "My Bikes: " & join(StringObjectReference("bar").Item("Bikes"), ", ")
' Shorthand notation (without item)
msgbox "My Quads: " & join(StringObjectReference("bar")("Quads"), ", ")
答案 1 :(得分:0)
在您使用字符串变量的内容来引用代码中的某些方法/函数/对象的瞬间,您将“失去”Option Explicit的好处。你可以在变量中放入任何你想要的东西,在代码执行之前不会对它进行测试。
但是你可以使用Option Explicit with Execute。这段代码
Dim D1
Set D1 = CreateObject("Scripting.Dictionary")
Execute "Option Explicit : D1.Add ""1"",""car"""
Execute "Option Explicit : D2 = D1.Item(""1"")"
WScript.Echo D1.Item("1")
会抱怨D2没有被定义。但它会在运行时完成。注释这一行,您将看到Add方法按预期工作。