这里有一种相对简单的方式将long转换为int,只需提取低32位而不抛出异常。无需进行64位除法,无需try/catch块,只需要进行位操作和一次比较。
Private Function CastLongToInt(x As Long) As Integer
Dim value As Integer = CType(x And &H7FFFFFFFL, Integer) ' get the low order 31 bits
' If bit 32 (the sign bit for a 32-bit signed integer is set, we OR it in
If (0 <> (x And &H80000000L)) Then
value = value Or &H80000000I
End If
Return value
End Function
这里有一个更简单的版本 - 只需进行位操作。完全没有比较。我们只需获取2个16位半字节并将它们组装成最终值:
Private Function CastLongToInt(x As Long) As Integer
Dim hiNibble As Integer = &HFFFFL And (x >> 16)
Dim loNibble As Integer = &HFFFFL And x
Dim value As Integer = (hiNibble << 16) Or loNibble
Return value
End Function
编辑说明:
另一个选项是使用可空整数(System.Nullable<int>
)。在VB.Net中,它会像这样:
Private Function TryCastLongToInt(x As Long) As Integer?
Dim value As Integer?
Try
value = CType(x, Integer)
Catch
' This exception intentionall swallowed here
End Try
Return value
End Function
或者,如果有意地捕获和吞咽异常的概念让您感到困扰:
Private Function TryCastLongToInt(x As Long) As Integer?
If (x < Integer.MinValue) Then Return Nothing
If (x > Integer.MaxValue) Then Return Nothing
Return x
End Function
无论如何,返回值将是一个整数值,或者如果64位值超出32位整数的范围,则返回
Nothing
。
Int.MaxValue
的 Long 值使用什么值? - D Stanley