基于继承或实现引入类型转换作。
注解
DirectCast 不使用 Visual Basic 运行时帮助程序例程进行转换,因此它可以提供比 CType 转换到数据类型和从数据类型 Object转换时更好的性能。
使用 DirectCast 关键字类似于使用 CType 运算符 和 TryCast 运算符 关键字的方式。 提供表达式作为第一个参数,并提供一个类型,以将其转换为第二个参数。
DirectCast 需要两个参数的数据类型之间的继承或实现关系。 这意味着一种类型必须继承或实现另一种类型。
错误和失败
DirectCast 如果检测到不存在继承或实现关系,则生成编译器错误。 但是缺少编译器错误不能保证成功转换。 如果所需的转换缩小,则它在运行时可能会失败。 如果发生这种情况,运行时将引发错误 InvalidCastException 。
转换关键字
类型转换关键字的比较如下所示。
| 关键字 | 数据类型 | 参数关系 | 运行时失败 |
|---|---|---|---|
| CType 运算符 | 任何数据类型 | 必须在两种数据类型之间定义扩大或缩小转换 | 抛出 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 为 Double.
CType 成功,因为 Double 可以转换为 Integer。 但是,第一个 DirectCast 在运行时失败,因为运行时类型 Double 没有与 Integer继承关系,即使存在转换。 第二 DirectCast 个成功,因为它从类型 Form 转换为类型 Control,从中 Form 继承。