我有一个类型为sbyte
的变量,想要将其内容复制到一个byte
中。这个转换不会是一个值转换,而是逐位复制。
例如,
如果我的sbyte在位上是:'10101100',转换后,相应的byte变量也将包含位'10101100'。
让我澄清一下unchecked
的作用。 MSDN页面指出,unchecked
用于防止溢出检查,否则,在checked上下文中,会导致编译错误或抛出异常。
...如果在checked上下文中。
这个上下文可以通过显式方式进行检查:
checked { ... }
或者隐式地,当处理编译时常量时:
byte b = (byte)-6; //compile error
byte b2 = (byte)(200 + 200); //compile error
int i = int.MaxValue + 10; //compiler error
但是在处理运行时变量时,默认情况下上下文是unchecked
:
sbyte sb = -6;
byte b = (byte)sb; //no problem, sb is a variable
int i = int.MaxValue;
int j = i + 10; //no problem, i is a variable
总结并回答原问题:
需要将常量从 byte<->sbyte
进行转换?使用 unchecked
和强制类型转换:
byte b = unchecked( (byte) -6 );
需要将 变量 从 byte<->sbyte
进行转换?只需进行强制类型转换:
sbyte sb = -6;
byte b = (byte) sb;
* 有第三种方法可以默认获取已检查的上下文:通过调整编译器设置。例如,Visual Studio -> 项目属性 -> 构建 -> 高级... -> [X] 检查算术溢出/下溢
** 在C#中,默认情况下运行时上下文是未检查的。例如,在VB.NET中,运行时上下文的默认值为CHECKED。
unchecked
{
sbyte s = (sbyte)250; //-6 (11111010)
byte b = (byte)s; //again 250 (11111010)
}
unchecked
{
sbyte s;
s= (sbyte)"your value";
byte b=(byte)s;
}
有关于unchecked
的更多信息,请查看此处
像这样:
sbyte sb = 0xFF;
byte b = unchecked((byte)sb);
byte
类型? - V4Vendettaunchecked
。有关完整详细信息,请参阅我的答案。 - Cristian Diaconescu