CType, DirectCast, TryCast语句

这三个都是类型转换函数,将一个对象的类型转换为另一个类型.CType和DirectCast是以前版本就有的, TryCast则是Visual Basic 2005才新加入的.它们的一般用法如下:

Dim p as product

p = CType(obj, Product)

p = DirectCast(obj, Product)

p =TryCast(obj, Product)

If p IsNot Nothing Then
 .....  
End If
 
 

 

DirectCast: 基于继承或实现的类型转换操作,DirectCast 不使用 Visual Basic 运行时帮助器例程进行转换,因此它可以提供比 CType 更好一些的性能。 使用 DirectCast 关键字的方法与使用 CType 函数和 TryCast 关键字相同: 提供一个表达式作为第一个参数,提供一个类型以将它转换为第二个参数。DirectCast 需要两个参数的数据类型之间的继承或实现关系。这意味着一个类型必须继承或实现另一个类型。
使用 TryCast 关键字的方法与使用 CType 函数和 DirectCast 关键字的方法相同。提供一个表达式作为第一个参数,并提供要将其转换成的类型作为第二个参数。TryCast 仅适用于引用类型,如类和接口。它要求这两种类型之间的关系为继承或实现。这意味着一个类型必须继承自或实现另一个类型。
在类型转换操作中,如果尝试转换失败,则 CType 和 DirectCast 都会引发 InvalidCastException 错误。这将给应用程序的性能造成负面影响。TryCast 返回 Nothing (Visual Basic),因此只需测试返回的结果是否为 Nothing,而无需处理可能产生的异常。
 
 以下是类型转换关键字的对比: 
 

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

 
 
 
 
 
 
 
 
 
  

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 继承自该类型。