TryCast 运算符 (Visual Basic)TryCast Operator (Visual Basic)

引入了不会引发异常的类型转换运算。Introduces a type conversion operation that does not throw an exception.

备注Remarks

如果尝试执行的转换失败,CTypeDirectCast同时引发InvalidCastException错误。If an attempted conversion fails, CType and DirectCast both throw an InvalidCastException error. 这会产生负面影响应用程序的性能。This can adversely affect the performance of your application. TryCast 返回Nothing,以便无需处理可能的异常,只需测试针对返回的结果NothingTryCast returns Nothing, so that instead of having to handle a possible exception, you need only test the returned result against Nothing.

您使用TryCast关键字使用的相同方式CType Function并且DirectCast 运算符关键字。You use the TryCast keyword the same way you use the CType Function and the DirectCast Operator keyword. 提供作为第一个参数,并将其转换为作为第二个参数的类型的表达式。You supply an expression as the first argument and a type to convert it to as the second argument. TryCast 只对引用类型,如类和接口执行操作。TryCast operates only on reference types, such as classes and interfaces. 它需要两个类型之间的继承或实现关系。It requires an inheritance or implementation relationship between the two types. 这意味着,必须继承自或实现另一种类型。This means that one type must inherit from or implement the other.

错误和失败Errors and Failures

TryCast 如果它检测到任何继承或实现关系不存在,将生成编译器错误。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. 如果发生这种情况,TryCast将返回NothingIf this happens, TryCast returns Nothing.

转换关键字Conversion Keywords

类型转换关键字的比较是按如下所示。A comparison of the type conversion keywords is as follows.

关键字Keyword 数据类型Data types 自变量的关系Argument relationship 运行时失败Run-time failure
CType 函数CType Function 任何数据类型Any data types 必须在两个数据类型之间定义扩大或收缩转换Widening or narrowing conversion must be defined between the two data types 将引发 InvalidCastExceptionThrows InvalidCastException
DirectCast 运算符DirectCast Operator 任何数据类型Any data types 一种类型必须继承自或实现另一个类型One type must inherit from or implement the other type 将引发 InvalidCastExceptionThrows InvalidCastException
TryCast 仅适用于引用类型Reference types only 一种类型必须继承自或实现另一个类型One type must inherit from or implement the other type 返回执行任何操作Returns Nothing

示例Example

下面的示例说明如何使用 TryCastThe following example shows how to use 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

请参阅See also