Visual Basic Programming Guide Implicit and Explicit Conversions
An implicit conversion does not require any special syntax in the source code.
In the following example, Visual Basic implicitly converts the value of k to a single-precision floating-point value before assigning it to q.
Dim k As Integer
Dim q As Double
' Integer widens to Double, so you can do this with Option Strict On.
k = 432
q = k
An explicit conversion uses a type conversion keyword.
Visual Basic provides several such keywords, which coerce an expression in parentheses to the desired data type.
These keywords act like functions, but the compiler generates the code inline, so execution is slightly faster than with a function call.
In the following extension of the preceding example, the CInt keyword converts the value of q back to an integer before assigning it to k.
' q had been assigned the value 432 from k.
q = Math.Sqrt(q)
k = CInt(q)
' k now has the value 21 (rounded square root of 432).
 Conversion Keywords
The following table shows the available conversion keywords.
|
Type conversion keyword
|
Converts an expression to data type
|
Allowable data types of expression to be converted
|
|
CBool
|
Boolean Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), String, Object
|
|
CByte
|
Byte Data Type (Visual Basic)
|
Any numeric type (including SByte and enumerated types), Boolean, String, Object
|
|
CChar
|
Char Data Type (Visual Basic)
|
String
, Object
|
|
CDate
|
Date Data Type (Visual Basic)
|
String
, Object
|
|
CDbl
|
Double Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CDec
|
Decimal Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CInt
|
Integer Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CLng
|
Long Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CObj
|
Object Data Type
|
Any type
|
|
CSByte
|
SByte Data Type (Visual Basic)
|
Any numeric type (including Byte and enumerated types), Boolean, String, Object
|
|
CShort
|
Short Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CSng
|
Single Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CStr
|
String Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, Char, Char array, Date, Object
|
|
CType
|
Type specified following the comma (,)
|
When converting to an elementary data type (including an array of an elementary type), the same types as allowed for the corresponding conversion keyword
When converting to a composite data type, the interfaces it implements and the classes from which it inherits
When converting to a class or structure on which you have overloaded CType, that class or structure
|
|
CUInt
|
UInteger Data Type
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CULng
|
ULong Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
|
CUShort
|
UShort Data Type (Visual Basic)
|
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
|
 The CType Function
The CType Function operates on two arguments.
The first is the expression to be converted, and the second is the destination data type or object class.
Note that the first argument must be an expression, not a type.
CType
is an inline function, meaning the compiled code makes the conversion, often without generating a function call.
This improves performance.
For a comparison of CType with the other type conversion keywords, see DirectCast and TryCast.
Elementary Types
The following example demonstrates the use of CType.
k = CType(q, Integer)
' The following statement coerces w to the specific object class Label.
f = CType(w, Label)
Composite Types
You can use CType to convert values to composite data types as well as to elementary types.
You can also use it to coerce an object class to the type of one of its interfaces, as in the following example.
' Assume class cZone implements interface iZone.
Dim h As Object
' The first argument to CType must be an expression, not a type.
Dim cZ As cZone
' The following statement coerces a cZone object to its interface iZone.
h = CType(cZ, iZone)
Array Types
CType
can also convert array data types, as in the following example.
Dim v() As classV
Dim obArray() As Object
' Assume some object array has been assigned to obArray.
' Check for run-time type compatibility.
If TypeOf obArray Is classV()
' obArray can be converted to classV.
v = CType(obArray, classV())
End If
For more information and an example, see Array Conversions.
Types Defining CType
You can define CType on a class or structure you have defined.
This allows you to convert values to and from the type of your class or structure.
For more information and an example, see How to: Define a Conversion Operator.
Note:
|
|
Values used with a conversion keyword must be valid for the destination data type, or an error occurs.
For example, if you attem
pt to convert a
Long to an Integer, the value of the Long must be within the valid range for the Integer data type.
|
Caution:
|
|
Specifying
CType to convert from one class type to another fails at run time if the source type does not derive from the destination type.
Such a failure throws an InvalidCastException exception.
|
However, if one of the types is a structure or class you have defined, and if you have defined CType on that structure or class, a conversion can succeed if it satisfies the requirements of your CType.
See How to: Define a Conversion Operator.
Performing an explicit conversion is also known as casting an expression to a given data type or object class.
 See Also
Tasks
Concepts
Reference
Other Resources
|
Guia de programação Visual Basic Conversões explícita e implícita
Uma conversão implícita não requer qualquer síntaxe especial no código fonte.
No exemplo a seguir, Visual Basic implicitamente converte o valor de k em um valor de ponto flutuante antes designá-lo a q.
Dim k As Integer
Dim q As Double
' Integer widens to Double, so you can do this with Option Strict On.
k = 432
q = k
Uma conversão explícita usa uma palavra-chave para a conversão de tipos.
Visual Basic fornece palavras-vários tal chave, que forçar uma expressão entre parênteses ao tipo de dados desejado.
Essas palavras-chave atuam como funções, mas o compilador gera o código embutido, portanto execução é ligeiramente mais rápido do que com um chamada de função.
Na seguinte extensão do exemplo anterior, a palavra-chave CInt converte o valor de q novamente como um número inteiro antes de atribuí-lo para k.
' q had been assigned the value 432 from k.
q = Math.Sqrt(q)
k = CInt(q)
' k now has the value 21 (rounded square root of 432).
 Palavras-chave conversão
A tabela a seguir mostra as palavras-chave conversão disponível.
|
Palavra-chave conversão tipo
|
Converte uma expressão em tipo de dados
|
Tipos de dados permitido de expressão a ser convertido
|
|
CBool
|
Tipo de dados booleanos (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), String, Object
|
|
CByte
|
Tipo de dados Byte (Visual Basic)
|
Qualquer tipo numérico (incluindo SByte, Boolean e os tipos enumerados), String, Object
|
|
CChar
|
Caractere tipo de dados (Visual Basic)
|
String
, Object
|
|
CDate
|
Tipo de dados Data (Visual Basic)
|
String
, Object
|
|
CDbl
|
Tipo de dados duplo (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CDec
|
Tipo de dados decimais (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CInt
|
Tipo de Dados Inteiro (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CLng
|
Tipo de dados Long (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CObj
|
Tipo de dados Object
|
Qualquer tipo
|
|
CSByte
|
Tipo de dado SByte (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, Boolean e os tipos enumerados), String, Object
|
|
CShort
|
Tipo de dados Short (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CSng
|
Tipo de dados único (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CStr
|
Tipo de dados de seqüência de caracteres (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, Char,matriz Char,Date,Object
|
|
CType
|
Tipo especificado após a vírgula (,)
|
Ao converter para um Tipo de dados elementar (incluindo uma matriz de um tipo elementar) os mesmos tipos como permitido para a palavra-chave conversão correspondente
Ao converter em interfaces um tipo de dados composto, o ele implementa e as classes do qual ele herda
Ao converter a uma classe ou estrutura na qual você tenha sobrecarregado CType, que classe ou estrutura
|
|
CUInt
|
Tipo de dados UInteger
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CULng
|
Tipo de dados ULong (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
|
CUShort
|
Tipo de dados UShort (Visual Basic)
|
Qualquer tipo numérico (incluindo Byte, SByte e os tipos enumerados), Boolean, String,Object
|
 A função CType
O CType Function opera em dois argumentos.
A primeira é a expressão a ser convertido, e o segundo é a classe tipo ou objeto de dados de destino.
Observe que o primeiro argumento deve ser uma expressão, não um tipo.
CType
é uma função in-line, que significa que o código compilado faz a conversão, com freqüência sem gerar um chamada de função.
Isso melhora o desempenho.
Para uma comparação de CType com as outras conversão de tipos palavras-chave, consulte DirectCast e TryCast.
Tipos elementar
O exemplo a seguir demonstra o uso de CType.
k = CType(q, Integer)
' The following statement coerces w to the specific object class Label.
f = CType(w, Label)
Tipos Composite
Você pode usar CType para converter valores em tipos de dados compostos bem como para tipos elementares.
Também pode usá-lo para forçar uma classe de objeto para o tipo de uma das suas interfaces, como no exemplo a seguir.
' Assume class cZone implements interface iZone.
Dim h As Object
' The first argument to CType must be an expression, not a type.
Dim cZ As cZone
' The following statement coerces a cZone object to its interface iZone.
h = CType(cZ, iZone)
Tipos de matriz
CType
também pode converter tipos de dados de matriz, como no exemplo a seguir.
Dim v() As classV
Dim obArray() As Object
' Assume some object array has been assigned to obArray.
' Check for run-time type compatibility.
If TypeOf obArray Is classV()
' obArray can be converted to classV.
v = CType(obArray, classV())
End If
Para mais informações e um exemplo, consulte Conversões de matriz.
Tipos definindo CType
Você pode definir CType em uma classe ou estrutura que você definiu.
Isso permite que você para converter valores de e para o tipo de sua classe ou estrutura.
Para mais informações e um exemplo, consulte Como: Definir um operador de conversão.
Observação:
|
|
Valores usados com uma palavra-chave conversão deve ser válido para o tipo de dados de destino, ou ocorrerá um erro.
Por exemplo, se você attem
pt para converter um
Long para um Integer, o valor do Long deve ser dentro do intervalo válido para o tipo de dados de Integer.
|
Cuidado:
|
|
Especificando
CType para converter de um tipo de classe para outro falha em tempo de execução se o tipo de origem não é derivada do tipo de destino.
Uma falha gera uma exceção InvalidCastException.
|
No entanto, se um dos tipos for uma classe ou estrutura que você definiu, e se você tiver definido CType nessa classe ou estrutura, uma conversão pode terá êxito se ele satisfaz os requisitos de seu CType.
See Como: Definir um operador de conversão.
Executar uma conversão explícita é também conhecido como Elenco uma expressão a uma classe tipo ou objeto de dados especificados.
 Consulte também
Tarefas
Conceitos
Referência
Outros recursos
|