gpt4 book ai didi

arrays - VBScript 嵌套类数据结构

转载 作者:行者123 更新时间:2023-12-03 23:47:50 24 4
gpt4 key购买 nike

我的问题可以用下面的示例代码来说明,它设置了一个 friend 的数据数组,每个 friend 可以有几个电话号码:

Class clsPhoneNo
Dim strType
Dim strNumber
End Class

Class clsPerson
Dim strName
Dim aclsPhoneNo()
End Class

Dim clsFriends()
ReDim clsFriends(3)
Set clsFriend(0) = New Person
clsFriend(0).strName = "Fred"
Set clsFriends(0).aclsPhoneNo(0) = New clsPhoneNo
ReDim clsFriend(0).aclsPhoneNo(2)
Set clsFriend(0).aclsPhoneNo(0).strType = "Home"
Set clsFriend(0).aclsPhoneNo(0) = "01234567890"
Set clsFriend(0).aclsPhoneNo(1).strType = "Work"
Set clsFriend(0).aclsPhoneNo(1) = "09876543210"

但是,VBScript 说
Microsoft VBScript compilation error: Expected end of statement

之前 。关于第二个 ReDim 语句

我需要使用 aclsPhoneNo 元素可变长度,因为我的代码并不是真正的地址簿,但这是一个演示该问题的简单示例。

有任何想法吗?

最佳答案

数组是解决这个问题的错误数据结构。它们是其他语言的首选武器,它们不是 VBScript,因为它们是出了名的不灵活。

考虑使用 Dictionaries 代替。并放弃匈牙利语。

Dim phoneBook: Set phoneBook = New ObjectList

With phoneBook.Append(New Person)
.Name = "fred"
.AddPhoneNo "Home", "01234567890"
.AddPhoneNo "Work", "09876543210"
End with

Dim pers: Set pers = phoneBook.Item(1)

For Each id In pers.PhoneNos.List
Set num = pers.PhoneNos.List(id)
WScript.Echo pers.Name & " #" & id & ": " & _
num.Number & " (" & num.Label & ")"
Next

' ------------------------------------------------------
Class ObjectList
Public List

Sub Class_Initialize()
Set List = CreateObject("Scripting.Dictionary")
End Sub

Sub Class_Terminate()
Set List = Nothing
End Sub

Function Append(Anything)
List.Add CStr(List.Count + 1), Anything
Set Append = Anything
End Function

Function Item(id)
If List.Exists(CStr(id)) Then
Set Item = List(CStr(id))
Else
Set Item = Nothing
End If
End Function
End Class

' ------------------------------------------------------
Class PhoneNo
Public Label
Public Number
End Class

' ------------------------------------------------------
Class Person
Public Name
Public PhoneNos

Sub Class_Initialize()
Set PhoneNos = New ObjectList
End Sub

Function AddPhoneNo(Label, Number)
Set AddPhoneNo = New PhoneNo
With PhoneNos.Append(AddPhoneNo)
.Label = Label
.Number = Number
End With
End Function
End Class

请注意,我在这里使用了一些 VB 功能
  • 您可以在脚本中定义函数和类之前使用它们,因此将所有管道放在底部。
  • 你可以有 PublicPrivate 类变量
  • 类有一个 Initiate 和一个 Terminate 事件,你可以对
  • 使用react
  • 函数名是变量声明。无需在函数中声明临时返回变量,您可以为此使用函数名称。
  • With 块也可以为您保存一个临时变量。
  • 字典虽然比较方便,但还是可以从方便的包装器中受益,所以我创建了一个。
  • 关于arrays - VBScript 嵌套类数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6565562/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com