日期:2014-05-16  浏览次数:21027 次

short类型,加上一个立即数,为什么编译错误?

        static void Main(string[] args)
        {
            short s = 1;
            s = s + 1;

有编译错误说是: error CS0266: Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

为什么s不能直接加一个整数,那么我要给s做算术运算,怎么办呢?
------解决方案--------------------
s有长度限制,不能用于运算,否则容易出现内存益出
------解决方案--------------------
s = (short)(s + 1);
------解决方案--------------------
Microsoft converts your Int16 variables into Int32 when doing the add function

s = (short)(s+1);

------解决方案--------------------
s + 1里面一个short类型一个int类型,不可以相加的