常量值不能转换为int

tpo*_*pol 2 c# .net-4.5

我不明白为什么第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)
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

编译时常量基本上与其他代码的检查方式不同.

除非您明确拥有unchecked表达式,否则将编译时常量强制转换为其范围不包含该值的类型将始终失败.演员在编译时进行评估.

但是,在执行时评估被分类为(而不是常量)的表达式的强制转换,并通过异常(在已检查的代码中)或通过截断位(在未经检查的代码中)来处理溢出.

您可以稍微更容易地看到这个byte,只是const字段与static readonly字段:

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
    }
}
Run Code Online (Sandbox Code Playgroud)