类模块数组属性 ByRef Variant Index
设置数组属性(ByRef),其中修改了传递的参数值,为何不能够改变被传址数组的值
如何使类的属性既能传递给数组,又能传递给数组的一个元素?
Class1.cls
Option Explicit
Private B() As Byte
Public Property Get mArray() As Byte() 'Optional bIndex As Variant
'If IsMissing(bIndex) Then
Let mArray = B()
'Else
'mArray = b(bIndex)
'End If
End Property
Rem 如何既能传递数组,又能传递数组的一个元素
Public Property Let mArray(ByRef vData() As Byte) 'Optional bIndex As Variant
'If IsMissing(bIndex) Then
Erase B()
Let B() = vData()
'Else
'b(bIndex) = vData(vIndex)
'End If
On Error GoTo ErrCancel:
If CStr((LBound(vData()))) <> "" Then
vData(LBound(vData())) = 123 '测试 Byref 是否能够改变被传址数组的值
End If
Stop
Exit Property
ErrCancel:
On Error GoTo 0
End Property
Public Property Let Test(ByRef mString As String, mStart As Long, Optional mLength As Variant, vData As String)
If IsMissing(mLength) Then
Mid(mString, mStart) = vData
Else
Mid(mString, mStart, mLength) = vData
End If
End Property
Public Property Get Test(mString As String, mStart As Long, Optional mLength As Variant) As String
If IsMissing(mLength) Then
Test = Mid(mString, mStart)
Else
Test = Mid(mString, mStart, mLength)
End If
End Property
Form1.frm
Option Explicit
Private Sub Command1_Click()
Dim Cls1 As Class1
Set Cls1 = New Class1
Dim B() As Byte
ReDim B(30) As Byte
Rem 测试1
Dim S As String
S = "abcdefg"
Cls1.Test(S, 1, 3) = "12"
Debug.Print Cls1.Test(S, 1, 3) 'Byref 起到作用
'__________________________________________
Debug.Print
Rem 测试2
B(LBound(B())) = 234
Let B() = Cls1.mArray()
On Error Resume Next
Debug.Print B(LBound(B())) 'Cause an error
ReDim B(10) As Byte
Let Cls1.mArray() = B() 'Byref 没有起到作用
Debug.Print B(LBound(B()))
Stop
End Sub
[解决办法]
对啊
只有 Property Let 类属性中才会这样
只能用 Sub 或 Function ( ) 才有办法用 ByRef 喔
[解决办法]
Property Let 与 Functiont 和 Sub 不同之处就
1是没有返回值
2是只能用于属性表达式或Let语句的左边
也就是你示例代码中:Let Cls1.mArray() = B() 这一行,对表达式右边的数组B没有作用,也就是B不作为返回值返回你的修改...
作为参数,数组缺省就是ByRef,但属性的参数(你代码中的vData)是由赋值表达式的右边传递的,这就是与 Functiont 和 Sub 的参数不同之处...所以只能说你代码中第二个Property Let似是而非,改变的并非与属性相关的vData....
[解决办法]
你这是写的什么呀。
很简单的:
Public Property Get mArray() As Byte()
mArray = B
End Property
Public Property Let mArray(vData() As Byte)
b=vdata
End Property
'给单个元素赋值
Public Property Let item(index as long, v as byte)
b(index)=v
End Property