如何在VBScript中的词典中使用对象?

时间:2019-03-12 11:05:39

标签: dictionary object vbscript

我创建了一个简单的类GaugeChart:

Class GaugeChart 
    Public Essential
    Public Lifestyle
    Public Spending
    Public Average
End Class

我想在字典中使用

   Dim items, objGaugeDic, objGaugeChart, objGaugeChartread
    Set objGaugeDic = CreateObject("Scripting.Dictionary")

    Set objGaugeChart = New GaugeChart  ' from GaugeChartClass.asp
    objGaugeChart.Essential = intChart1Essential
    objGaugeChart.Lifestyle = intChart1Lifestyle
    objGaugeChart.Spending = intChart1Spending
    objGaugeChart.Average = Chart1Avg
    Set objGaugeDic ("Goal1") = objGaugeChart 
    Response.Write("Essential: " + Cstr(objGaugeChart.Essential) + "<br />")


    Set objGaugeChart = New GaugeChart  ' from GaugeChartClass.asp
    objGaugeChart.Essential = intChart2Essential
    objGaugeChart.Lifestyle = intChart2Lifestyle
    objGaugeChart.Spending = intChart2Spending
    objGaugeChart.Average = Chart2Avg
    Set objGaugeDic ("Goal2") = objGaugeChart 


    ' load values
    'objGuageDic.Add "Goal1", objGaugeElements
    Response.Write("objGaugeDic Keys: " + Cstr(objGaugeDic.Count))

    For i = 0 To objGaugeDic.Count -1 'Iterate the array
        Response.Write( CType(objGaugeDic.Item(i),objGaugeChart).Essential + "<br />")

    Next

字典键= 2-很好。但是,当我尝试使用CType访问字典中的对象和属性时,会出现运行时错误。

尝试objGaugeDic.Item(i).Essential时我不确定。

我也尝试过,而不是Set objGaugeDic ("Goal1") = objGaugeChart, to do objGaugeDic.Add“ Goal1”,objGaugeChart`。

如何访问objGaugeDic类型的每个Response.Write( CType(objGaugeDic.Item(i),objGaugeChart).Essential + "<br />")字典项的对象属性?

1 个答案:

答案 0 :(得分:0)

您可以通过For Each循环内的键来引用字典中的对象:

For Each strKey In objGaugeDic
    Response.Write(objGaugeDic(strKey).Essential + "<br />")
Next

此外,您可能会在循环外获得一个键数组,并通过索引按索引引用字典中的对象:

arrKeys = objGaugeDic.Keys()
For i = 0 To objGaugeDic.Count -1
    Response.Write(objGaugeDic(arrKeys(i)).Essential + "<br />")
Next