我正在尝试在 vbscript 中创建一个类,该类将字典作为其成员变量之一,并为其 Add 方法创建一个简单的包装器类。这确实很糟糕。我评论过...
我正在尝试在 vbscript 中创建一个类,该类将字典作为其成员变量之一,并为其 Add 方法创建一个简单的包装器类。这确实很糟糕。我已注释掉所有不起作用的行。
Class ConfigSection
Private m_Name
' A dictionary of values to set {Section:{name:value, name2:value2}}
Private m_Values
Private m_Overwrite
Public Function init(p_Name, p_Overwrite)
Set init = Me
m_Name = p_name
m_Overwrite = p_Overwrite
'Values = CreateObject("Scripting.Dictionary")
End Function
Public Property Get Name
Name = m_Name
End Property
Public Property Get Overwrite
Overwrite = m_Overwrite
End Property
Public Sub Add(Name, Value)
'Values().Add Name, Value
End Sub
'Private Property Let Values(Value)
' Set m_Values = Value
'End Property
End Class
不建议通过公开成员变量来暴露它们。要暴露字典,请正确包装您想要在类的属性和方法中访问的属性和方法。
允许添加、更改和删除键/值对以及检查键是否存在的示例:
Class Foo
Private d_
Private Sub Class_Initialize
Set d_ = CreateObject("Scripting.Dictionary")
End Sub
Public Property Let Item(name, value)
d_(name) = value
End Property
Public Property Get Item(name)
Item = d_(name)
End Property
Public Function Exists(name)
Exists = d_.Exists(name)
End Function
Public Sub Remove(name)
d_.Remove(name)
End Sub
End Class
Set obj = New Foo
WScript.Echo "" & obj.Exists("bar")
obj.Item("bar") = 42
WScript.Echo "" & obj.Exists("bar")
WScript.Echo obj.Item("bar")
obj.Remove("bar")
WScript.Echo "" & obj.Exists("bar")
逐行浏览注释行:
Values = CreateObject("Scripting.Dictionary")
在将对象引用分配给变量时 Set
需要使用
Values().Add Name, Value
您需要先定义一个 Property Get
for Values
才能访问它。否则,它是一个只写属性。
Private Property Let Values(Value)
Set m_Values = Value
End Property
由于此属性包含对象引用,因此必须使用关键字 Property Set
.
综合起来:
Class ConfigSection
Private m_Name
' A dictionary of values to set {Section:{name:value, name2:value2}}
Private m_Values
Private m_Overwrite
Public Function init(p_Name, p_Overwrite)
Set init = Me
m_Name = p_name
m_Overwrite = p_Overwrite
Set Values = CreateObject("Scripting.Dictionary")
End Function
Public Property Get Name
Name = m_Name
End Property
Public Property Get Overwrite
Overwrite = m_Overwrite
End Property
Public Sub Add(Name, Value)
Values().Add Name, Value
End Sub
Private Property Get Values
Set Values = m_Values
End Property
Private Property Set Values(Value)
Set m_Values = Value
End Property
End Class