本文介绍了按字符串变量的 VbScript 引用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过字符串变量引用对象?我觉得除了使用执行和丢失选项显式

How can I reference an object by a string variable? I feel like there has at be a way to do this other than than using execute and losing Options Explicit

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

Example (where "Something is the command / method in question":

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

strObj = "D1"

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

谢谢!

推荐答案

只有 functions(和 subs)可以被 Set functionReference = GetRef("myFunction") 但不是对象.

Only functions (and subs) can be referenced by Set functionReference = GetRef("myFunction") but not objects.

当你想要一个字符串引用时,你必须为每个你想要引用的对象创建一个.您可以为此使用字典:

When you want to have a string reference, you have to create one with each object you would want to refer to. You can use a dictionary for that:

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"), ", ")

这篇关于按字符串变量的 VbScript 引用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:04