为什么在unsigned int上的移位操作给出无符号结果,但是对较小的无符号操作数的操作会导致一个带符号的int?
int signedInt = 1; int shiftedSignedInt = signedInt << 2; uint unsignedInt = 1; uint shiftedUnsignedInt = unsignedInt << 2; //OK. unsigned result short signedShort = 1; int shiftedsignedShort = signedShort << 2; ushort unsignedShort = 1; uint shiftedUnsignedShort = unsignedShort << 2; //CS0266: Can't cast int to uint sbyte signedByte = 1; int shiftedSignedByte = signedByte << 2; byte unsignedByte = 1; uint shiftedUnsignedByte = unsignedByte << 2; //CS0266: Can't cast int to uint
解决方法
shift operators仅为这些情况预定义(向左移动):
int operator <<(int x,int count); (1) uint operator <<(uint x,int count); (2) long operator <<(long x,int count); (3) ulong operator <<(ulong x,int count); (4)
表达式uint shifUnignedShort = unsignedShort<<< 2被解释为(1)-st情况(implicit up-casting from ushort to int和(int)2),所以它对非法投射执行了一个警告(没有int结果到隐含的转换).
同样的情况我们可以看到uint shifUnsignedByte = unsignedByte<<<它还解释为(1)-st情况(从字节到int和(int)2的隐式升级,但没有将结果值隐式转换为uint). 您可以使用以下方法解决这些问题:
uint shiftedUnsignedShort = (uint)unsignedShort << 2 //force use the (2)-nd shift operator case uint shiftedUnsignedByte = (uint)unsignedByte << 2; //force use the (2)-nd shift operator case