清理Scripting.Dictionary的初始化

时间:2014-01-09 16:26:38

标签: dictionary vbscript initialization

我在名为ProcessBook的应用程序中使用VBScript,我希望将一些静态信息存储在字典中。

我正在尝试干净地初始化这个字典,而不需要调用单独的程序,但我尝试的方法似乎都没有。

这是我到目前为止所尝试的内容:

Dim myDict As New Dictionary(Of String, String) (("key1", "item1"), ("key2", "item2"))
Dim myDict As Variant
Set myDict = New Dictionary( ("key1", "item1"), ("key2", "item2") )

基本上是一堆涉及这种形式的猜测。

到目前为止,我能做的最好的事情是:

With myDict
.add "key1", "item1"
.add "key2", "item2"
End With

但是当我不想进入常规时,这会让我感到咆哮。我希望避免这种情况。

我相信(Of type,type)From {}语法超出VB 6.5

有没有人知道在VB 6.5中初始化scripting.dictionary的一些简洁方法?

2 个答案:

答案 0 :(得分:1)

6.5大概是指VBA?如果是这样,则无法在例程之外操作/初始化对象实例。

唯一的方法是将其封装在类(cDict)中并使用构造函数:

Private mDict As Scripting.Dictionary

Private Sub Class_Initialize()
    Set mDict = New Scripting.Dictionary
    With mDict
        .Add "key1", "item1"
        .Add "key2", "item2"
    End With
End Sub

Public Property Get Dict() As Scripting.Dictionary
    Set Dict = mDict
End Property

然后在客户端模块中;

Private Dict As New cDict

Sub foo()
    MsgBox Dict.Dict.Item("key1")
    Dict.Dict.Add "key3", "item3"
    MsgBox Dict.Dict.Item("key3")
End Sub

Of type与VB.Net Generics有关)

答案 1 :(得分:1)

VBA实际上是一种PROCEDURAL语言,而不是面向对象语言,因此答案是使用一个过程。 怎么做......

Option Explicit
Option Compare Text

Sub test()
    Dim dic As New Scripting.Dictionary
    Add dic, Array("Darren", 123, "Alex", 321)
    MsgBox dic.Count
End Sub

Public Sub Add(dic As Dictionary, values As Variant)
    If Not IsArray(values) Then
        Err.Raise -1, "Add", "Values must be varient Array"
    ElseIf UBound(values) Mod 2 = 0 Then
        Err.Raise -1, "Add", "Even number of values required"
    End If
    Dim iQ As Long
    For iQ = 0 To UBound(values) Step 2
        dic.Add values(iQ), values(iQ + 1)
    Next
End Sub