Compartilhar via


Declaração Const (Visual Basic)

Declares and defines one or more constants.

[ <attributelist> ] [ accessmodifier ] [ Shadows ] 
Const constantlist

Parts

  • attributelist
    Optional. List of attributes that apply to all the constants declared in this statement. See Lista de atributos (Visual Basic) in angle brackets ("<" and ">").

  • accessmodifier
    Optional. Use this to specify what code can access these constants. Can be Público (Visual Basic), Protegido (Visual Basic), Friend (Visual Basic), Protected Friend, or Private (Visual Basic).

  • Shadows
    Optional. Use this to redeclare and hide a programming element in a base class. See Shadows.

  • constantlist
    Required. List of constants being declared in this statement.

    constant [ , constant ... ]

    Each constant has the following syntax and parts:

    constantname [ As datatype ] = initializer

    Part

    Description

    constantname

    Required. Name of the constant. See Nomes de elementos declarados (Visual Basic).

    datatype

    Required if Option Strict is On. Data type of the constant.

    initializer

    Required. Expression that is evaluated at compile time and assigned to the constant.

Comentários

If you have a value that never changes in your application, you can define a named constant and use it in place of a literal value. A name is easier to remember than a value. You can define the constant just once and use it in many places in your code. If in a later version you need to redefine the value, the Const statement is the only place you need to make a change.

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

Local constants (inside a procedure) default to public access, and you cannot use any access modifiers on them. Class and module member constants (outside any procedure) default to private access, and structure member constants default to public access. You can adjust their access levels with the access modifiers.

Rules

  • Declaration Context. Uma constante declarada no nível de módulo , fora de qualquer procedimento, é um constante de membro; é um membro da classe, estruturaou módulo que declara que ele.

    A constant declared at procedure level is a local constant; it is local to the procedure or block that declares it.

  • Atributos. You can apply attributes only to member constants, not to local constants. An attribute contributes information to the assembly's metadata, which is not meaningful for temporary storage such as local constants.

  • Modificadores. Por padrão, todas as constantes são Shared, Static, e ReadOnly. You cannot use any of these keywords when declaring a constant.

    At procedure level, you cannot use Shadows or any access modifiers to declare local constants.

  • Multiple Constants. Você pode declarar diversas constantes na mesma declaração demonstrativo, especificando a constantname parte de cada um. Multiple constants are separated by commas.

Data Type Rules

  • Tipos de dados. O Constdedemonstrativo pode declarar o tipo de dados de uma variável. You can specify any data type or the name of an enumeration.

  • Default Type. Se você não especificar datatype, a constante leva o tipo de dados de initializer. If you specify both datatype and initializer, the data type of initializer must be convertible to datatype. If neither datatype nor initializer is present, the data type defaults to Object.

  • Different Types. Você pode especificar diferentes tipos de dados para constantes diferentes usando um separado As cláusula para cada variável que você declarar. However, you cannot declare several constants to be of the same type by using a common As clause.

  • Inicialização. Você deve inicializar o valor de cada constante na constantlist. You use initializer to supply an expression to be assigned to the constant. The expression can be any combination of literals, other constants that are already defined, and enumeration members that are already defined. You can use arithmetic and logical operators to combine such elements.

    You cannot use variables or functions in initializer. However, you can use conversion keywords such as CByte and CShort. You can also use AscW if you call it with a constant String or Char argument, since that can be evaluated at compile time.

Behavior

  • Escopo. Local constants are accessible only from within their procedure or block. Member constants are accessible from anywhere within their class, structure, or module.

  • Qualification. Code outside a class, structure, or module must qualify a member constant's name with the name of that class, structure, or module. Code outside a procedure or block cannot refer to any local constants within that procedure or block.

Exemplo

The following example uses the Const statement to declare constants for use in place of literal values.

' The following statements declare constants. 
Const maximum As Long = 459
Public Const helpString As String = "HELP"
Private Const startValue As Integer = 5

If you define a constant with data type Object, the Visual Basic compiler gives it the type of initializer, instead of Object. In the following example, the constant naturalLogBase has the run-time type Decimal.

Const naturalLogBase As Object = CDec(2.7182818284)
MsgBox("Run-time type of constant naturalLogBase is " & 
    naturalLogBase.GetType.ToString())

The preceding example uses the ToString method on the Type object returned by the Operador GetType (Visual Basic), because Type cannot be converted to String using CStr.

Consulte também

Referência

Declaração Enum (Visual Basic)

Diretriz #Const

Instrução Dim (Visual Basic)

instrução ReDim (Visual Basic)

Funções de conversão de tipo (Visual Basic)

Asc

AscW

Conceitos

Conversões explícitas e implícitas (Visual Basic)

Constantes e Enumerações (Visual Basic)

Outros recursos

Constantes e Enumerations no Visual Basic