Ben*_*ell 7 c# syntax bitwise-operators implicit-cast
short BitwiseTest(short value)
{
short test1 = ((value >> 8) & 0xFF);
short test2 = unchecked((short)((value << 8) & 0xFF00));
return (test1 | test2);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应该是一个(低效)示例,它在C#中交换短(带符号的16位整数)的字节序.
但是上面的代码不会编译,因为C#在以下两行中隐式地从short转换为int:
第一种情况:
short test1 = ((value >> 8) & 0xFF);
Run Code Online (Sandbox Code Playgroud)
第二种情况:
return (test1 | test2);
Run Code Online (Sandbox Code Playgroud)
为什么要进行演员表演?我是否可以通过简短的回归来实现预期的结果?像这样:
short BitwiseTest2(short value)
{
short test1 = (short)((value >> 8) & 0xFF);
short test2 = unchecked((short)((value << 8) & 0xFF00));
return ((short)(test1 | test2));
}
Run Code Online (Sandbox Code Playgroud)
如果不是为什么不呢?
请注意,我确实理解为什么C#在执行左位移时将短路转换为整数,因此分配了test2变量.