我在 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 这样的十进制数保存到 session 中,然后我尝试将其作为整数检索,那么我想抛出 InvalidCastException。 DirectCast
做得很好。
但是,我想允许扩大转换(例如,将 5 这样的整数保存到 session 中,然后将其作为小数检索)。 DirectCast
不允许这样做,但是 CType
允许。不幸的是,CType
还允许缩小转换,这意味着在第一个示例中,它将返回值 6。
有没有一种方法可以实现我想要的行为?也许通过使用 VB 的 Catch...When
过滤异常?
最佳答案
模数我在评论中留下的关于此的警告,您实际上可以捕捉到 CType 允许的缩小转换。 Type.GetTypeCode() 方法是一种按大小对值类型进行排序的便捷方法。使这段代码工作:
Public Function LoadFromSession(Of T)(sessionKey As String) As T
Dim value As Object = SBSSession(sessionKey)
Try
If Type.GetTypeCode(value.GetType()) > Type.GetTypeCode(GetType(T)) Then
Throw New InvalidCastException()
End If
Return CType(value, T)
Catch ex As NullReferenceException
Return Nothing
End Try
End Function
我看到的唯一古怪的是它允许从 Char 转换为 Byte。
关于vb.net - 在 VB 中允许扩大转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19234724/