Share via


Operador TryCast (Visual Basic)

Apresenta uma operação de conversão de tipo que não gera uma exceção.

Comentários

Se uma tentativa de conversão falhar, CType e DirectCast ambos lançam um InvalidCastException erro. Isso pode afetar o desempenho do seu aplicativo. TryCastRetorna Nada (Visual Basic), de modo que, em vez de ter que lidar com uma possível exceção, você precisa somente de teste o resultado retornado contra Nothing.

You use the TryCast keyword the same way you use the Função CType (Visual Basic) and the Operador DirectCast (Visual Basic) keyword. Você fornecer uma expressão como o primeiro argumento e um tipo de converter -lo para como o segundo argumento. TryCastopera somente em tipos de referência, como, por exemplo, classes e interfaces. Ele requer uma relação entre os dois tipos de herança ou implementação. This means that one type must inherit from or implement the other.

Errors and Failures

TryCast 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. Se isso acontecer, TryCast retorna Nada (Visual Basic).

Conversion Keywords

A comparison of the type conversion keywords is as follows.

Keyword

Data types

Argument relationship

Run-time failure

Função CType (Visual Basic)

Any data types

Widening or narrowing conversion must be defined between the two data types

Throws InvalidCastException

Operador DirectCast (Visual Basic)

Any data types

One type must inherit from or implement the other type

Throws InvalidCastException

TryCast

Reference types only

One type must inherit from or implement the other type

Returns Nada (Visual Basic)

Exemplo

O exemplo a seguir mostra como usar TryCast.

Function PrintTypeCode(ByVal obj As Object) As String
    Dim objAsConvertible As IConvertible = TryCast(obj, IConvertible)
    If objAsConvertible Is Nothing Then
        Return obj.ToString() & " does not implement IConvertible"
    Else
        Return "Type code is " & objAsConvertible.GetTypeCode()
    End If
End Function

Consulte também

Conceitos

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

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