允许在VB中扩展转换

时间:2013-10-07 21:02:07

标签: vb.net casting type-conversion

我在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

过滤异常

2 个答案:

答案 0 :(得分:3)

在评论中模拟我留下的关于此的警告,您实际上可以捕获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。

答案 1 :(得分:1)

由于缩小不是一般的想法,如评论中所述,最好检查类型并按照您想要的方式转换特定案例:

dim q as object = SBSSession(sessionKey)
If q.GetType Is GetType(System.Int32) Then ...

普遍缩小和扩大的问题在于它不是单向关系。有时一对类型可以包含另一个不能的值。

相关问题