2

我想将字典作为参数传递。我的代码可能看起来有点奇怪,但我还是会展示它:

Sub get_Insurers_Dictionary()

Dim cInsurers               As c_Insurers
Dim myDictionary            As Scripting.Dictionary

Set cInsurers = New c_Insurers

Set myDictionary = New Scripting.Dictionary
Set myDictionary = cInsurers.Get_Parameters_Dictionary(cInsurers, myDictionary)

End Sub

然后在 c_Insurers 类中:

Public Function Get_Parameters_Dictionary(cInsurers As c_Insurers, myDictionary As Dictionary) As Dictionary

Dim oSheet                      As Excel.Worksheet
Dim cParameters                 As c_Parameters


Set oSheet = ThisWorkbook.Sheets("Parameters_Insurers")
oSheet.Activate

Set cParameters = New c_Parameters
Set cParameters = cParameters.Get_Parameters(cParameters, oSheet)

Me.fPartner_ID_Col = cParameters.get_Header_Cols(oSheet, cParameters.fMax_Col, "INSURER_ID")
Me.fPartner_Name_Col = cParameters.get_Header_Cols(oSheet, cParameters.fMax_Col, "INSURER_NAME")
Me.fCountry_Col = cParameters.get_Header_Cols(oSheet, cParameters.fMax_Col, "COUNTRY")

For lcnt = 1 To UBound(cParameters.fArray)
    myDictionary.Add cParameters.fArray(lcnt, Me.fPartner_ID_Col), Me.Get_Parameters_Class(cInsurers, cParameters, lcnt)
Next lcnt

Set Get_Parameters_Insurers = myDictionary
Set cParameters = Nothing

End Function

除了看似复杂的代码,我的问题很简单:甚至可以添加一个类对象作为项目吗?(我还不习惯使用字典)。我的字典在 c_insurers 类中填写,但是当我回到 get_Insurers_Dictionary 时为什么它是空的?

4

1 回答 1

1

您可以将您喜欢的任何内容添加到字典中,它的行为与您预期的不同,因为您将字典传递给Get_Parameters_Dictionary但在填充后您永远不会返回它,而是将其分配给其他东西;Set Get_Parameters_Insurers = myDictionary.

这意味着Set myDictionary = cInsurers.Get_Parameters_Dictionary(cInsurers, myDictionary)重置myDictionaryNothing(因为未分配的返回类型)。

您需要进入Set Get_Parameters_Dictionary = myDictionaryGet_Parameters_Dictionary()……不打扰;字典是引用类型,所以之后:

Set myDictionary = New Scripting.Dictionary
cInsurers.Get_Parameters_Dictionary cInsurers, myDictionary

myDictionary将反映在 中所做的更改Get_Parameters_Dictionary

于 2012-06-11T12:13:45.210 回答