如何在类中初始化数组属性?如何在下面初始化array1:
class Class1
private count
private array1
private sub class_initialize
count = 0
array1(0) = 0 'initialize first element
end sub
end class
导致错误: Microsoft VBScript运行时错误'800a000d'类型不匹配:'array1'
答案 0 :(得分:1)
我明白了:
class Class1
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
end class
答案 1 :(得分:0)
因为改革后的班级无法正常运作且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子。