我有一个类,其成员是一个双精度数组
'cls_Person
Public Name as String
Public InAMeeting as Variant
'InAMeeting: Type: Array of Double.
'Sometimes with dimensions of 1 to 8, sometimes of 1 to 10.
我用循环填充我的类,然后用字符串作为键将它们填充到全局字典中。
当我尝试直接从字典访问 InAMeeting 成员时,我的问题出现了:
'g_dict_People is a globally defined dictionary.
'KeyPerson is a unique key in the dictionary matching a filled object of type cls_Person
Dim Bravo as Double
Bravo = g_dict_People(KeyPerson).InAMeeting(3)
导致错误: 属性let 过程未定义,属性获取过程未返回对象(错误 451(
但是如果我首先从字典中创建对象的副本,那么它可以工作:
Dim Bravo as Double
Set temp_cls_Person = g_dict_People(KeyPerson)
Bravo = temp_cls_Person.InAMeeting(3)
我可以直接访问 Name 成员 - 这有效:
Dim Alpha as string
Alpha = g_dict_People(KeyPerson).Name
为什么会有差异?这与我在类定义中声明 InAMeeting 成员的方式有关吗?当对象为数组类型时,有没有办法直接访问它们的成员?
抱歉,我没有详细说明一个最小的工作示例 - 代码分布在多个模块和类中。
由于我们没有 MCVE,我无法测试您的代码,但以下代码对我有用。 根据这个答案修改。 TIL 是()
的另一个用例! 尝试:
Bravo = g_dict_People(KeyPerson).InAMeeting()(3)
' extra parens! ^^
InAMeeting
显然是作为一个属性实现的,即一个函数,你必须调用它来获取你想要索引的数组。 额外的()
打这个电话。
我的测试用例:
类1.cls
Public v As Variant
此文档.bas
Public Sub foo()
Dim v As Variant
v = Array(1#, 2#, 3#, 4#, 5#) ' Assuming you're doing something like this
Dim o As Class1 ' Put the variant array in the object
Set o = New Class1
o.v = v
Dim c As Collection ' Put the object in the collection
Set c = New Collection
c.Add o, "key"
On Error Resume Next
Err.Clear
Debug.Print "Direct"
Debug.Print v(3) ' Works OK
Debug.Print Err.Number, Err.Description
Err.Clear
Debug.Print "From collection with ()"
Debug.Print c("key").v()(3) ' <== Your use case - works OK
' Extra parens ^^
Debug.Print Err.Number, Err.Description
' Reproducing the problem
Err.Clear
Debug.Print "From collection"
Debug.Print c("key").v(3) ' <== Bombs --- I think this is analogous to your use case
Debug.Print Err.Number, Err.Description
Err.Clear
Dim o1 As Object
Set o1 = c("key")
Debug.Print "Intermediate object"
Debug.Print o1.v(3) ' Trying what you tried, but it didn't work for me.
Debug.Print Err.Number, Err.Description
' Another thing that works
Err.Clear
Debug.Print "Intermediate object with ()"
Debug.Print o1.v()(3) ' <== This works
' Those extra ^^ parens
Debug.Print Err.Number, Err.Description
End Sub