gpt4 book ai didi

arrays - 数组作为类成员

转载 作者:行者123 更新时间:2023-12-02 04:40:09 25 4
gpt4 key购买 nike

我正在为传出消息设计一个动态缓冲区。数据结构采用节点队列的形式,其中包含字节数组缓冲区作为成员。不幸的是,在 VBA 中,数组不能是类的公共(public)成员。

例如,这是一个禁忌,并且不会编译:

'clsTest

Public Buffer() As Byte

您将收到以下错误:“常量、定长字符串、数组、用户定义类型和 Declare 语句不允许作为对象模块的公共(public)成员”

好吧,没关系,我只需将其设为具有公共(public)属性访问器的私有(private)成员...

'clsTest

Private m_Buffer() As Byte

Public Property Let Buffer(buf() As Byte)
m_Buffer = buf
End Property

Public Property Get Buffer() As Byte()
Buffer = m_Buffer
End Property

...然后在模块中进行一些测试以确保其正常工作:

'mdlMain

Public Sub Main()
Dim buf() As Byte
ReDim buf(0 To 4)

buf(0) = 1
buf(1) = 2
buf(2) = 3
buf(3) = 4


Dim oBuffer As clsTest
Set oBuffer = New clsTest

'Test #1, the assignment
oBuffer.Buffer = buf 'Success!

'Test #2, get the value of an index in the array
' Debug.Print oBuffer.Buffer(2) 'Fail
Debug.Print oBuffer.Buffer()(2) 'Success! This is from GSerg's comment

'Test #3, change the value of an index in the array and verify that it is actually modified
oBuffer.Buffer()(2) = 27
Debug.Print oBuffer.Buffer()(2) 'Fail, diplays "3" in the immediate window
End Sub

测试 #1 工作正常,但是测试 #2 中断,Buffer 突出显示,错误消息为“参数数量错误或属性分配无效”

测试 #2 现在可以工作了! GSerg 指出,为了正确调用 Property Get Buffer() 并引用缓冲区中的特定索引,需要两组括号: oBuffer.Buffer()(2)

测试 #3 失败 - 原始值 3 被打印到“立即”窗口。 GSerg 在评论中指出,Public Property Get Buffer() 仅返回一个副本,而不是实际的类成员数组,因此修改会丢失。

如何解决第三个问题,使类成员数组按预期工作?

(我应该澄清,一般问题是“VBA 不允许数组成为类的公共(public)成员。我怎样才能解决这个问题,让类的数组成员的行为就好像它是为所有实际目的包括:#1 分配数组,#2 从数组获取值,#3 在数组中分配值,#4 直接在调用 CopyMemory 中使用数组(#3 和 # 4 几乎相等)?)”

最佳答案

事实证明我需要 OleAut32.dll 的一些帮助,特别是 'VariantCopy'功能。此函数忠实地将一个变体复制到另一个变体,包括当它是 ByRef 时!

'clsTest

Private Declare Sub VariantCopy Lib "OleAut32" (pvarDest As Any, pvargSrc As Any)

Private m_Buffer() As Byte

Public Property Let Buffer(buf As Variant)
m_Buffer = buf
End Property

Public Property Get Buffer() As Variant
Buffer = GetByRefVariant(m_Buffer)
End Property

Private Function GetByRefVariant(ByRef var As Variant) As Variant
VariantCopy GetByRefVariant, var
End Function

有了这个新定义,所有测试都通过了!

'mdlMain

Public Sub Main()
Dim buf() As Byte
ReDim buf(0 To 4)

buf(0) = 1
buf(1) = 2
buf(2) = 3
buf(3) = 4


Dim oBuffer As clsTest
Set oBuffer = New clsTest

'Test #1, the assignment
oBuffer.Buffer = buf 'Success!

'Test #2, get the value of an index in the array
Debug.Print oBuffer.Buffer()(2) 'Success! This is from GSerg's comment on the question

'Test #3, change the value of an index in the array and verify that it is actually modified
oBuffer.Buffer()(2) = 27
Debug.Print oBuffer.Buffer()(2) 'Success! Diplays "27" in the immediate window
End Sub

关于arrays - 数组作为类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25328975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com