结构和其他编程元素 (Visual Basic)

可以将结构与数组、对象和过程以及彼此结合使用。 交互使用的语法与这些元素单独使用的语法相同。

注释

不能初始化结构声明中的任何结构元素。 只能将值分配给已声明为结构类型的变量的元素。

结构和数组

结构可以包含数组作为其一个或多个元素。 下面的示例对此进行了演示。

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"  

还可以使用此技术将一个模块中定义的结构封装在不同的模块中定义的结构中。

结构可以包含任意深度的其他结构。

另请参阅