【问题标题】:VbScript Reference Object by String variable字符串变量的 VbScript 引用对象
【发布时间】:2013-11-26 01:42:20
【问题描述】:

如何通过字符串变量引用对象?我觉得除了使用执行和丢失选项显式之外,还有其他方法可以做到这一点

示例(其中“某事是有问题的命令/方法”:

Dim strObj
Dim D1 : Set D1 = CreateObject("Scripting.Dictionary")

strObj = "D1"

Something(strObj).add "1" , "Car"    
msgbox Something(strObj).Item("1") 

谢谢!

【问题讨论】:

  • 请退后一步,描述您要解决的实际问题,而不是您认为的解决方案。为什么你认为你需要这个?为了什么?
  • 即使你不想退后一步描述问题——试着理解你自己的问题,然后向我们解释,因为完全不清楚你在说什么。
  • 你说得对,我的例子没有任何意义。我纠正了它。所以问题是我在 HTA 中从 2 个不同的来源填充 2 个不同的字典,但随后希望能够使用基于用户选择构建 Div 的 innerhtml 的相同功能。将参数(字典对象名称)传递给函数以确定要使用的对象,而不是使用 if 语句并拥有编写 HTML 的所有代码......每个字典一次。问题是关于 VB 中的动态引用,例如可以在 html 中使用 getobjectbyid()

标签: vbscript


【解决方案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"), ", ")

【讨论】:

  • 天哪,您可以将 Object 实例存储在 scripting.dictionary 对象中!!!?!脑洞大开。叮叮……赢家!支持您 AutomatedChaos 知道我在说什么,即使是一个蹩脚的草率例子!
  • 谢谢这是完美的。
【解决方案2】:

在您使用字符串变量的内容来引用代码中的某些方法/函数/对象的那一刻,您“失去”了 Option Explicit 的好处。您可以将任何您想要的内容放入变量中,并且在执行代码之前不会对其进行测试。

但您可以将 Option Explicit 与 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 方法按预期工作。

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 2012-01-29
    • 2011-04-22
    • 2016-04-28
    • 2014-10-03
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多