DirectCast 运算符 (Visual Basic)

引入基于继承或实现的类型转换操作。

注解

DirectCast 不将 Visual Basic 运行时帮助程序例程用于转换,因此它可以提供比 CType 在数据类型 Object 中转换时更好的性能。

使用 DirectCast 关键字的方式与使用 CType 函数TryCast 运算符关键字的方式相同。 提供表达式作为第一个参数,并将类型转换为第二个参数。 DirectCast 要求两个参数的数据类型之间的继承关系或实现关系。 这意味着一种类型必须从另一种类型继承或实现另一种类型。

错误和故障

如果 DirectCast 检测到不存在继承或实现关系,则会生成编译器错误。 但是没有编译器错误并不能保证转换成功。 如果所需的转换是收缩转换,则其可能会在运行时失败。 如果发生这种情况,运行时将引发 InvalidCastException 错误。

转换关键字

下面是类型转换关键字的对比。

关键字 数据类型 参数关系 运行时失败
CType Function 任何数据类型 必须在这两种数据类型之间定义扩大转换或收缩转换 引发 InvalidCastException
DirectCast 任何数据类型 一种类型必须从另一种类型继承或实现另一种类型 引发 InvalidCastException
TryCast 运算符 仅限引用类型 一种类型必须从另一种类型继承或实现另一种类型 返回 Nothing

示例

下面的示例演示 DirectCast 的两个用法,一个运行时失败,另一个成功。

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)

在上述示例中,q 的运行时类型为 DoubleCType 成功,因为 Double 可以转换为 Integer。 但是,第一个 DirectCast 运行时失败,因为 Double 的运行时类型与 Integer 没有继承关系,即使存在转换。 第二个 DirectCast 成功,因为它从类型 Form 转换为 Form 继承的类型 Control

另请参阅