Conversões explícitas e implícitas (Visual Basic)
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 BasicFornece palavras-vários tal chave, que forçar uma expressão entre parênteses para o tipo de dadosde desejado. 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 |
Any numeric type (including Byte, SByte, and enumerated types), String, Object |
|
CByte |
Any numeric type (including SByte and enumerated types), Boolean, String, Object |
|
CChar |
String, Object |
|
CDate |
String, Object |
|
CDbl |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CDec |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CInt |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CLng |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CObj |
Any type |
|
CSByte |
Any numeric type (including Byte and enumerated types), Boolean, String, Object |
|
CShort |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CSng |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CStr |
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 |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CULng |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
|
CUShort |
Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object |
The CType Function
The Função CType (Visual Basic) 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 Operador DirectCast (Visual Basic) and Operador TryCast (Visual Basic).
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 Conversões de matriz (Visual Basic).
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 Como: Definir um operador de conversão (Visual Basic).
Observação |
---|
Values used with a conversion keyword must be valid for the destination data type, or an error occurs. For example, if you attempt to convert a Long to an Integer, the value of the Long must be within the valid range for the Integer data type. |
Aviso
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 Como: Definir um operador de conversão (Visual Basic).
Performing an explicit conversion is also known as casting an expression to a given data type or object class.
Consulte também
Tarefas
Como: Converter um objeto para outro tipo no Visual Basic
Solucionando problemas de tipos de dados (Visual Basic)
Referência
Resumo de tipo de dados (Visual Basic)
Funções de conversão de tipo (Visual Basic)
Conceitos
Alterações de valor durante conversões (Visual Basic)
Conversões entre sequências e outros tipos (Visual Basic)
Programação Sem-Tipos no Visual Basic