您可以結合使用資料結構與陣列、物件和程序,以及彼此之間一起使用。 互動操作採用的語法和這些元素單獨使用時相同。
備註
您無法初始化結構宣告中的任何結構專案。 您只能將值指派給已宣告為 結構類型的變數元素。
結構和陣列
結構可以包含陣列做為其一個或多個元素。 下列範例說明這點。
Public Structure systemInfo
Public cPU As String
Public memory As Long
Public diskDrives() As String
Public purchaseDate As Date
End Structure
您可以在 結構中存取陣列的值,就像存取 物件上的屬性一樣。 下列範例說明這點。
Dim mySystem As systemInfo
ReDim mySystem.diskDrives(3)
mySystem.diskDrives(0) = "1.44 MB"
您也可以宣告結構的陣列。 下列範例說明這點。
Dim allSystems(100) As systemInfo
您可以遵循相同的規則來存取此資料架構的元件。 下列範例說明這點。
ReDim allSystems(5).diskDrives(3)
allSystems(5).CPU = "386SX"
allSystems(5).diskDrives(2) = "100M SCSI"
結構和物件
結構可以包含物件作為其中一個或多個元素。 下列範例說明這點。
Protected Structure userInput
Public userName As String
Public inputForm As System.Windows.Forms.Form
Public userFileNumber As Integer
End Structure
您應該在這類宣告中使用特定的物件類別,而不是 Object。
結構和程式
您可以傳遞 結構做為程式自變數。 下列範例說明這點。
Public currentCPUName As String = "700MHz Pentium compatible"
Public currentMemorySize As Long = 256
Public Sub fillSystem(ByRef someSystem As systemInfo)
someSystem.cPU = currentCPUName
someSystem.memory = currentMemorySize
someSystem.purchaseDate = Now
End Sub
上述範例 會以傳址方式傳遞 結構,讓程式修改其元素,讓變更在呼叫程式代碼中生效。 如果您想要保護結構不受這類修改,請依值傳遞它。
您也可以從 Function 程式傳回 結構。 下列範例說明這點。
Dim allSystems(100) As systemInfo
Function findByDate(ByVal searchDate As Date) As systemInfo
Dim i As Integer
For i = 1 To 100
If allSystems(i).purchaseDate = searchDate Then Return allSystems(i)
Next i
' Process error: system with desired purchase date not found.
End Function
結構中的結構
結構可以包含其他結構。 下列範例說明這點。
Public Structure driveInfo
Public type As String
Public size As Long
End Structure
Public Structure systemInfo
Public cPU As String
Public memory As Long
Public diskDrives() As driveInfo
Public purchaseDate As Date
End Structure
Dim allSystems(100) As systemInfo
ReDim allSystems(1).diskDrives(3)
allSystems(1).diskDrives(0).type = "Floppy"
您也可以使用這項技術,將一個模組中定義的結構封裝在不同的模塊中定義的結構中。
結構可以包含任意深度的其他結構。