因为reformed 的类不能正常工作并且ShadowWizards 的评论很危险:
Option Explicit
class ArrMemberA
private count
private array1
private sub class_initialize
count = 0
array1 = array() 'initialize array property
end sub
'to add a new element to array property
public sub add(input)
redim preserve array1(count + 1)
array1(count) = input
count = count + 1
end sub
Public Function toString()
toString = "[" & Join(array1, "*") & "]"
End Function
end class
Class ArrMemberB
Private m_a
Private Sub Class_Initialize
m_a = Array() ' initialize to empty dynamic array
End Sub
Public Sub add(input)
ReDim Preserve m_a(UBound(m_a) + 1)
m_a(UBound(m_a)) = input
End Sub
Public Function toString()
toString = "[" & Join(m_a, "*") & "]"
End Function
End Class
Class ArrMemberC
Private m_a()
Public Sub add(input)
ReDim Preserve m_a(UBound(m_a) + 1)
m_a(UBound(m_a)) = input
End Sub
Public Function toString()
toString = "[" & Join(m_a, "*") & "]"
End Function
End Class
Class ArrMemberD
Private m_a()
Private m_n
Private Sub Class_Initialize
m_n = -1 ' initialize to empty ubound
End Sub
Public Sub add(input)
m_n = m_n + 1
ReDim Preserve m_a(m_n)
m_a(m_n) = input
End Sub
Public Function toString()
toString = "[" & Join(m_a, "*") & "]"
End Function
End Class
Dim a : Set a = New ArrMemberA
a.add "zero"
a.add "one"
WScript.Echo "a:", a.toString(), "- spurious empty tail element"
Dim b : Set b = New ArrMemberB
b.add "zero"
b.add "one"
WScript.Echo "b:", b.toString()
Dim c : Set c = New ArrMemberC
On Error Resume Next
c.add "zero"
WScript.Echo "c:", Err.Description, "- Ubound() fails for the abomination created by 'Private m_a()'"
On Error GoTo 0
Dim d : Set d = New ArrMemberD
d.add "zero"
d.add "one"
WScript.Echo "d:", d.toString()
输出:
cscript demoarray.vbs
a: [zero*one*] - spurious empty tail element
b: [zero*one]
c: Subscript out of range - Ubound() fails for the abomination created by 'Private m_a()'
d: [zero*one]
(a) 表明自己掷牌是有风险的;(b) 按我的方式行事;(c) 证明“Dim/Private/Public varname()”的结果不能是 UBound();(d) 证明“要使其工作”,您需要您试图避免的 Class_Initialize 子。