Wrong number of arguments or invalid property assignment using classes

爱⌒轻易说出口 提交于 2021-02-10 19:47:16

问题


Could anyone explain why I get this error on line 12? It is clearly an array. Why can I not obtain the value in index position 0 in this way? Do I really need that extra variable (arr)?

Option Explicit

Dim obj
Set obj = new ClsTest

obj.singleval = "test"
MsgBox obj.singleval                     ' test

obj.repeatingval = split ("a,b,c", ",")
MsgBox IsArray(obj.repeatingval)         ' true
MsgBox UBound(obj.repeatingval)          ' 2
MsgBox obj.repeatingval(0)               ' Wrong number of arguments or invalid
                                         ' property assignment: 'repeatingval'
Dim arr : arr = obj.repeatingval
MsgBox IsArray(arr)                      ' true
MsgBox UBound(arr)                       ' 2
MsgBox arr(0)                            ' a

Class ClsTest
    Private m_singleval
    Private m_repeatingval

    Public Property Get singleval()
        singleval = m_singleval
    End Property

    Public Property Let singleval(w)
        m_singleval = w
    End Property

    Public Property Get repeatingval()
        repeatingval = m_repeatingval
    End Property

    Public Property Let repeatingval(w)
        m_repeatingval = w
    End Property
End Class

回答1:


If you want indexed access to the (array) property repeatingval you need to change the property definition to include an index. Beware, though, that getter and setter must be defined alike:

Class ClsTest
    ...
    Public Property Get repeatingval(i)
        repeatingval = m_repeatingval(i)
    End Property

    Public Property Let repeatingval(i, w)
        m_repeatingval(i) = w
    End Property
End Class

You can't have a property where the setter takes an array and the getter returns an element of that array. To be able to assign an array and retrieve an element of that array, you need 2 different properties:

Class ClsTest
    ...
    Public Property Get repeatingval(i)
        repeatingval = m_repeatingval(i)
    End Property

    Public Property Let repeatingval(i, w)
        m_repeatingval(i) = w
    End Property

    Public Property Get repeatingarr
        repeatingval = m_repeatingval
    End Property

    Public Property Let repeatingarr(w)
        m_repeatingval = w
    End Property
End Class

Set obj = New ClsTest

obj.repeatingarr = Split("a,b,c", ",")
MsgBox IsArray(obj.repeatingarr)
MsgBox UBound(obj.repeatingarr)
MsgBox obj.repeatingval(0)



回答2:


Dim thing
For Each thing in obj.repeatingval
    msgbox thing
Next

This will give you access to it.



来源:https://stackoverflow.com/questions/27093706/wrong-number-of-arguments-or-invalid-property-assignment-using-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!