Instrução Structure

Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises.

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Partial ] _
Structure name [ ( Of typelist ) ]
    [ Implements interfacenames ]
    datamemberdeclarations
    [ methodmemberdeclarations ]
End Structure

Parts

Term

Definition

attributelist

Optional. See Attribute List.

accessmodifier

Optional. Can be one of the following:

See Níveis de acesso em Visual Basic.

Shadows

Optional. See Shadows.

Partial

Optional. Indicates a partial definition of the structure. See Partial (Visual Basic).

name

Required. Name of this structure. See Nomes de elementos declarados (Visual Basic).

Of

Optional. Specifies that this is a generic structure.

typelist

Required if you use the Of keyword. List of type parameters for this structure. See Type List.

Implements

Optional. Indicates that this structure implements the members of one or more interfaces. See Implementa Declaração.

interfacenames

Required if you use the Implements statement. The names of the interfaces this structure implements.

datamemberdeclarations

Required. One or more Const, Dim, Enum, or Event statements declaring data members of the structure.

methodmemberdeclarations

Optional. Zero or more declarations of Function, Operator, Property, or Sub procedures, which serve as method members of the structure.

End Structure

Required. Terminates the Structure definition.

Comentários

The Structure statement defines a composite value type that you can customize. A structure is a generalization of the user-defined type (UDT) of previous versions of Visual Basic. For more information, see Estruturas (Visual Basic).

Structures support many of the same features as classes. For example, structures can have properties and procedures, they can implement interfaces, and they can have parameterized constructors. However, there are significant differences between structures and classes in areas such as inheritance, declarations, and usage. Also, classes are reference types and structures are value types. For more information, see Estruturas e Classes (Visual Basic).

You can use Structure only at namespace or module level. This means the declaration context for a structure must be a source file, namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see Contextos de declaração e níveis de acesso padrão (Visual Basic).

Structures default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more information, see Níveis de acesso em Visual Basic.

Rules

  • Aninhamento. You can define one structure within another. The outer structure is called the containing structure, and the inner structure is called a nested structure. However, you cannot access a nested structure's members through the containing structure. Instead, you must declare a variable of the nested structure's data type.

  • Member Declaration. You must declare every member of a structure. A structure member cannot be Protected or Protected Friend because nothing can inherit from a structure. The structure itself, however, can be Protected or Protected Friend.

    You must declare at least one nonshared variable or nonshared, noncustom event in a structure. You cannot have only constants, properties, and procedures, even if some of them are nonshared.

  • Inicialização. You cannot initialize the value of any nonshared data member of a structure as part of its declaration. You must either initialize such a data member by means of a parameterized constructor on the structure, or assign a value to the member after you have created an instance of the structure.

  • Herança. Uma estrutura não pode herdar de qualquer tipo diferente de ValueType, da qual todas as estruturas herdam. In particular, one structure cannot inherit from another.

    You cannot use the Declaração Inherits in a structure definition, even to specify ValueType.

  • Implementação. Se a estrutura usa a Implementa Declaração, você deve implementar cada membro definido por cada interface que você especificar na interfacenames.

  • Padrão Propriedade. Uma estrutura pode especificar no máximo uma propriedade como sua propriedadepadrão de, usando o Padrão (Visual Basic) modificador. For more information, see Padrão (Visual Basic).

Behavior

  • Nível de acesso. Within a structure, you can declare each member with its own access level. All structure members default to Público (Visual Basic) access. Note that if the structure itself has a more restricted access level, this automatically restricts access to its members, even if you adjust their access levels with the access modifiers.

  • Escopo. A structure is in scope throughout its containing namespace, class, structure, or module.

    The scope of every structure member is the entire structure.

  • O tempo de vida. A structure does not itself have a lifetime. Rather, each instance of that structure has a lifetime independent of all other instances.

    The lifetime of an instance begins when it is created by a operador New (Visual Basic) clause. It ends when the lifetime of the variable that holds it ends.

    You cannot extend the lifetime of a structure instance. An approximation to static structure functionality is provided by a module. For more information, see Declaração de Módulo.

    Structure members have lifetimes depending on how and where they are declared. For more information, see "Lifetime" in Declaração Class (Visual Basic).

  • Qualification. Code outside a structure must qualify a member's name with the name of that structure.

    If code inside a nested structure makes an unqualified reference to a programming element, Visual Basic searches for the element first in the nested structure, then in its containing structure, and so on out to the outermost containing element. For more information, see Referências a elementos declarados (Visual Basic).

  • Memory Consumption. As with all composite data types, you cannot safely calculate the total memory consumption of a structure by adding together the nominal storage allocations of its members. Furthermore, you cannot safely assume that the order of storage in memory is the same as your order of declaration. If you need to control the storage layout of a structure, you can apply the StructLayoutAttribute attribute to the Structure statement.

Exemplo

The following example uses the Structure statement to define a set of related data for an employee. It shows the use of Public, Friend, and Private members to reflect the sensitivity of the data items. It also shows procedure, property, and event members.

Public Structure employee
    ' Public members, accessible from throughout declaration region.
    Public firstName As String
    Public middleName As String
    Public lastName As String
    ' Friend members, accessible from anywhere within the same assembly.
    Friend employeeNumber As Integer
    Friend workPhone As Long
    ' Private members, accessible only from within the structure itself.
    Private homePhone As Long
    Private level As Integer
    Private salary As Double
    Private bonus As Double
    ' Procedure member, which can access structure's private members.
    Friend Sub calculateBonus(ByVal rate As Single)
        bonus = salary * CDbl(rate)
    End Sub
    ' Property member to return employee's eligibility.
    Friend ReadOnly Property eligible() As Boolean
        Get
            Return level >= 25
        End Get
    End Property
    ' Event member, raised when business phone number has changed.
    Public Event changedWorkPhone(ByVal newPhone As Long)
End Structure

Consulte também

Referência

Declaração Class (Visual Basic)

Declaração Interface (Visual Basic)

Declaração de Módulo

Instrução Dim (Visual Basic)

Declaração Const (Visual Basic)

Declaração Enum (Visual Basic)

Declaração de evento

Instrução Operator

Propriedade declaração

Conceitos

Estruturas e Classes (Visual Basic)