Compartilhar via


Como: Chamar um procedimento de operador (Visual Basic)

You call an operator procedure by using the operator symbol in an expression. In the case of a conversion operator, you call the Função CType (Visual Basic) to convert a value from one data type to another.

You do not call operator procedures explicitly. Você simplesmente usar o operador, ou o CTypefunção, em uma instrução de atribuição ou uma expressão, da mesma maneira que você normalmente usa um operador. Visual Basictorna a chamada para oprocedimentode operador.

Defining an operator on a class or structure is also called overloading the operator.

To call an operator procedure

  1. Use the operator symbol in an expression in the ordinary way.

  2. Be sure the data types of the operands are appropriate for the operator, and in the correct order.

  3. The operator contributes to the value of the expression as expected.

To call a conversion operator procedure

  1. Use CType inside an expression.

  2. Be sure the data types of the operands are appropriate for the conversion, and in the correct order.

  3. CType calls the conversion operator procedure and returns the converted value.

Exemplo

The following example creates two TimeSpan structures, adds them together, and stores the result in a third TimeSpan structure. The TimeSpan structure defines operator procedures to overload several standard operators.

Dim firstSpan As New TimeSpan(3, 30, 0)
Dim secondSpan As New TimeSpan(1, 30, 30)
Dim combinedSpan As TimeSpan = firstSpan + secondSpan
Dim s As String = firstSpan.ToString() & 
          " + " & secondSpan.ToString() & 
          " = " & combinedSpan.ToString()
MsgBox(s)

Because TimeSpan overloads the standard + operator, the previous example calls an operator procedure when it calculates the value of combinedSpan.

For an example of calling a conversation operator procedure, see Como: Usar uma classe que define operadores (Visual Basic).

Compilando o código

Be sure the class or structure you are using defines the operator you want to use.

Consulte também

Tarefas

Como: Definir um operador (Visual Basic)

Como: Definir um operador de conversão (Visual Basic)

Como: Declarar uma estrutura (Visual Basic)

Referência

Instrução Operator

Expansão (Visual Basic)

Restrição (Visual Basic)

Instrução Structure

Conceitos

Procedimentos de operador (Visual Basic)

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

Conversões de expansão e restrição (Visual Basic)