唉,点解没有个“剪切”或“摘抄”的文章类型呢?我写的这些,既不完全是转载,又不能说是原创,也不能说是翻译。
引用 :http://www.jb51.net/article/37944.htm中说的:
在C#中有Checked与Unchecked ,对于因为整数类型参与算术操作和类型转换时产生的“溢出异常”——System.OverflowException,在某些算法来讲不算真正的“异常”,相反这种溢出常常为程序所用。C#通过引入checked和unchecked关键字来控制这种特殊情况的需求。它们都可以加于一个语句块前(如:checked{……}),或者一个算术表达式前(如:unchecked(x+y)),其中加checked标志的语句或表达式如果发生算术溢出,则抛出System.OverflowException类型的异常,而加unchecked标志的语句发生算术溢出时,则不抛出异常。unchecked只是将溢出的位丢弃而得到剩下的32位组成的十进制整数值。值得指出的是可以用“/checked”编译器选项指定整个文件的代码为checked语义,如果没有指定则默认为unchecked。如果同时在程序代码中指定checked或unchecked标志,又有了checked编译器选项,则除了标志为unchecked的代码外,其余的都有checked语义。
而在VB.NET中没有Checked与Unchecked,网上有介绍说,关闭编译器选项,具体操作是:项目 ---> 项目属性 ---> 编译 ----> 高级编译选项 ----> 优化 -- [不做整数溢出检查],试过可行。
在网上找到了如下解决办法,试过可行:http://stackoverflow.com/questions/2403154/fastest-way-to-do-an-unchecked-integer-addition-in-vb-net
<StructLayout(LayoutKind.Explicit)> Public Structure UncheckedInteger <FieldOffset(0)> Private longValue As Long <FieldOffset(0)> Private intValueLo As Integer <FieldOffset(4)> Private intValueHi As Integer Private Sub New(newLongValue As Long) longValue = newLongValue End Sub Public Overloads Shared Widening Operator CType(value As Long) As UncheckedInteger Return New UncheckedInteger(value) End Operator Public Overloads Shared Widening Operator CType(value As UncheckedInteger) As Long Return value.longValue End Operator Public Overloads Shared Widening Operator CType(value As UncheckedInteger) As Integer Return value.intValueLo End Operator Public Overloads Shared Operator *(x As UncheckedInteger,y As Integer) As UncheckedInteger Return New UncheckedInteger(x.longValue * y) End Operator Public Overloads Shared Operator Xor(x As UncheckedInteger,y As Integer) As UncheckedInteger Return New UncheckedInteger(x.longValue Xor y) End Operator ' Any other operator overload you need... End Structure
使用方法:
C#中代码: unchecked((int)121474836478); //返回结果为:1215752190
VB.net代码:
’处理类型转换中溢出
Dim x As UncheckedInteger =121474836478 ‘ x 的结果为:1215752190
x=2
'处理运算中溢出
Dim x As UncheckedInteger =2
Dim resultAsInteger= x*2147483647 ' This would throw OverflowException using just Integers
' result 的结果为 :-2
原文链接:https://www.f2er.com/vb/258128.html