arrays - 如何在 ASP classic 中初始化类中的数组属性?

标签 arrays asp-classic vbscript

如何初始化类中的数组属性?下面如何初始化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”

最佳答案

因为 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 子项。

关于arrays - 如何在 ASP classic 中初始化类中的数组属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16258941/

相关文章:

java - 将新对象分配给通用数组索引

caching - 经典asp中应用程序对象的大小限制是多少?

class - .hta语法错误,创建类

java - 如何从标题为全名缩写的列表生成 .txt 文件

arrays - 访问元组数组 Swift 4

html - 无法运行 asp 文件。而是被提示下载所说的 asp 文件

xml - 在 VBScript 中格式化 XML 字符串

windows - 将变量从 vbscript 传递到批处理文件

arrays - 有没有更好的方法来可视化数组?

asp-classic - 赢得 CE 和 ASP : How to read/write a file?