我在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这样的整数保存到会话中,然后将其检索为十进制)。DirectCast不允许这样做,但是CType允许。不幸的是,CType还允许缩小转换,这意味着在第一个示例中,它将返回值6。
有什么方法可以达到我想要的行为吗?也许是通过使用VB的Catch...When过滤异常
发布于 2013-10-08 03:33:58
模块我在注释中留下的警告,您实际上可以捕捉到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的转换。
发布于 2013-10-08 03:18:38
由于缩窄在一般情况下并不是一个好主意,正如注释中提到的那样,检查类型并以您想要的方式转换特定情况可能更好:
dim q as object = SBSSession(sessionKey)
If q.GetType Is GetType(System.Int32) Then ...总体缩小和扩大的问题是,它不是单向的关系。有时,一对类型可以包含另一种类型不能包含的值。
https://stackoverflow.com/questions/19234724
复制相似问题