我不明白为什么第 5 行无法编译,而第 4 行却可以。
static void Main(string[] args)
{
byte b = 0;
int i = (int)(0xffffff00 | b); // ok
int j = (int)(0xffffff00 | (byte)0); // error: Constant value cannot be converted to a 'int' (use 'unchecked' syntax to override)
}
基本上,编译时常量的检查方式与其他代码不同。
将编译时常量转换为范围不包含该值的类型总是会失败,除非您明确地有一个unchecked
表达。转换是在编译时评估的。
然而,被分类为的表达式的强制转换value(而不是常量)在执行时计算,并通过异常(在检查的代码中)或通过截断位(在未检查的代码中)处理溢出。
您可以使用更轻松地看到这一点byte
和只是一个const
场对战static readonly
field:
class Test
{
static readonly int NotConstant = 256;
const int Constant = 256;
static void Main(string[] args)
{
byte okay = (byte) NotConstant;
byte fail = (byte) Constant; // Error; needs unchecked
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)