Operador DirectCast (Visual Basic)
Introduces a type conversion operation based on inheritance or implementation.
Comentários
DirectCast does not use the Visual Basic run-time helper routines for conversion, so it can provide somewhat better performance than CType when converting to and from data type Object.
You use the DirectCast keyword the same way you use the Função CType (Visual Basic) and the Operador TryCast (Visual Basic) keyword. Você fornecer uma expressão como o primeiro argumento e um tipo de converter -lo para como o segundo argumento. DirectCastrequer uma relação de herança ou implementação entre os tipos de dados dos dois argumentos. This means that one type must inherit from or implement the other.
Errors and Failures
DirectCast generates a compiler error if it detects that no inheritance or implementation relationship exists. But the lack of a compiler error does not guarantee a successful conversion. If the desired conversion is narrowing, it could fail at run time. If this happens, the runtime throws an InvalidCastException error.
Conversion Keywords
A comparison of the type conversion keywords is as follows.
Keyword |
Data types |
Argument relationship |
Run-time failure |
Any data types |
Widening or narrowing conversion must be defined between the two data types |
Throws InvalidCastException |
|
DirectCast |
Any data types |
One type must inherit from or implement the other type |
Throws InvalidCastException |
Reference types only |
One type must inherit from or implement the other type |
Returns Nada (Visual Basic) |
Exemplo
The following example demonstrates two uses of DirectCast, one that fails at run time and one that succeeds.
Dim q As Object = 2.37
Dim i As Integer = CType(q, Integer)
' The following conversion fails at run time
Dim j As Integer = DirectCast(q, Integer)
Dim f As New System.Windows.Forms.Form
Dim c As System.Windows.Forms.Control
' The following conversion succeeds.
c = DirectCast(f, System.Windows.Forms.Control)
No exemplo anterior, o tempo de execução-tipo de q é Double. CTypeé bem-sucedida pois Double pode ser convertido em Integer. However, the first DirectCast fails at run time because the run-time type of Double has no inheritance relationship with Integer, even though a conversion exists. The second DirectCast succeeds because it converts from type Form to type Control, from which Form inherits.