有没有用VB6的,讨论一下溢出问题,很有意思,同样的问题跟c#对比一下.
--------------------
在VB6(我是指vb6,vb.net中我没试过) 中,下面的代码会提示溢出的
Private Sub Command1_Click()
    Dim val1 As Integer
    Dim val2 As Double
    val1 = 32767
   '以下这句会提示溢出,因为32768已经超出integer的范围了.
   '当然,我知道,将其改成:val2 = clng(val1) + 1 就
   '不会溢出了,但是我不改,我就是为了说明问题
    val2 = val1 + 1
    MsgBox val2
End Sub以上代码中,val1的值是32767,加上1,便是32768了,正好超出integer的取值范围(-32768~+32767)
但是它并没有超出左边 val2的范围呀,val2可是声明的long型呀。
我认为这是VB设计的不合理之处。同样的情况,在C#下是不会存在的。
因为在c#中,short型与VB中的integer型的取值范围完全相同,
C#中的int型正好与VB6中的long型的取值范围也完全一样,所以可做全面的类比
代码如下,做一下类比        static void Main(string[] args)
        {
            short val1 = 32767;
            int val2;
    //以下这一句是不会提示溢出的
            val2 = val1 + 1;
            Console.WriteLine(val2);
            Console.ReadKey();        }

解决方案 »

  1.   

    short x = 5, y = 12;
    以下赋值语句将产生一个编译错误,原因是赋值运算符右侧的算术表达式在默认情况下的计算结果为 int 类型。
    short z = x + y; // Error: no conversion from int to short 
    若要解决此问题,请使用强制转换:
    short z = ( short )(x + y); // OK: explicit conversion 
    C#的short表达式在默认情况下的计算结果为 int 类型。
      

  2.   

    C# Language Reference7.2.6.2 Binary numeric promotionsBinary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here: If either operand is of type decimal, the other operand is converted to type decimal, or an error occurs if the other operand is of type float or double. 
    Otherwise, if either operand is of type double, the other operand is converted to type double. 
    Otherwise, if either operand is of type float, the other operand is converted to type float. 
    Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or an error occurs if the other operand is of type sbyte, short, int, or long. 
    Otherwise, if either operand is of type long, the other operand is converted to type long. 
    Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int, both operands are converted to type long. 
    Otherwise, if either operand is of type uint, the other operand is converted to type uint. 
    Otherwise, both operands are converted to type int. 由此可见,C#的数值表达式至少转换为 int 进行计算。