我正在VB中编写以下代码:
Public Shared Function LoadFromSession(Of T)(sessionKey As String) As T
Try
' Note: SBSSession is simply a reference to HttpContext.Current.Session
Dim returnValue As T = DirectCast(SBSSession(sessionKey), T)
Return returnValue
Catch ex As NullReferenceException
' If this gets thrown, then the object was not found in session. Return default value ("Nothing") instead.
Dim returnValue As T = Nothing
Return returnValue
Catch ex As InvalidCastException
' Instead of throwing this exception, I would like to filter it and only
' throw it if it is a type-narrowing cast
Throw
End Try
End Function
我希望做的是,在任何缩小转换的情况下抛出异常。例如,如果我将十进制数5.5保存到会话中,然后尝试将其作为整数检索,则希望引发InvalidCastException异常。DirectCast可以很好地完成这一点。
但是,我想允许扩展转换(例如,将整数5保存到会话中,然后将其作为十进制数检索)。DirectCast不允许这样做,但是CType可以。不幸的是,CType也可以进行缩小转换,这意味着在第一个示例中,它将返回值6。
是否有一种方法可以实现所需的行为?也许通过使用VB的Catch...When过滤异常?