VB.NET中的TryCast和direct cast是什么?
可能重复:VB.NET中的TryCast和direct cast是什么?,vb.net,Vb.net,可能重复: 我想知道VB.NET中的TryCast和DirectCast。它们之间的区别是什么?和(或)之间的主要区别是CType和DirectCast都将抛出,特别是在转换失败时抛出。这是一个潜在的“昂贵”操作 相反,如果指定的强制转换失败或无法执行,则TryCast操作符将返回Nothing,而不会引发任何异常。这可能会稍微提高性能 TryCast、DirectCast和CType的MSDN文章说得最好: 如果尝试的转换失败, CType和DirectCast都会抛出 InvalidCas
我想知道VB.NET中的
TryCast
和DirectCast
。它们之间的区别是什么?和(或)之间的主要区别是CType
和DirectCast
都将抛出,特别是在转换失败时抛出。这是一个潜在的“昂贵”操作
相反,如果指定的强制转换失败或无法执行,则TryCast
操作符将返回Nothing
,而不会引发任何异常。这可能会稍微提高性能
TryCast
、DirectCast
和CType
的MSDN文章说得最好:
如果尝试的转换失败,
CType
和DirectCast
都会抛出
InvalidCastException
错误。这个可以
对公司业绩产生不利影响
你的申请<代码>TryCast返回
无任何内容
(Visual Basic),以便
而不是必须处理一个可能的问题
异常,您只需要测试
没有返回结果
而且:
DirectCast
不使用可视
的基本运行时帮助程序例程
转换,所以它可以提供一些
性能优于CType
转换为数据类型和从数据类型转换
对象
简言之:
TryCast
将返回设置为Nothing
的对象,如果要转换的类型不是指定的类型
如果要转换的对象类型不是指定的类型,DirectCast
将引发异常
与TryCast
相比,DirectCast
的优势在于DirectCast
使用更少的资源,而且性能更好
代码示例:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim auto As Car = New Car()
' animalItem will be Nothing
Dim animalItem As Animal = GetAnimal_TypeCast(auto)
Dim cat As Cat = New Cat()
' animalItem will be Cat as it's of type Animal
animalItem = GetAnimal_TypeCast(cat)
Try
animalItem = GetAnimal_DirectCast(auto)
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(ex.Message)
End Try
End Sub
Private Function GetAnimal_TypeCast(ByVal animalType As Object) As Object
Dim animalBase As Animal
' This will produce an object set to Nothing if not of type Animal
animalBase = TryCast(animalType, Animal)
Return animalBase
End Function
Private Function GetAnimal_DirectCast(ByVal animalType As Object) As Object
Dim animalBase As Animal
' This will throw an exception if not of type Animal
animalBase = DirectCast(animalType, Animal)
Return animalBase
End Function
Dup:听起来好像你会建议总是使用TryCast而不是DirectCast。您应该更好地指出,DirectCast应该用作标准,只有在强制转换可能失败时才使用TryCast。