Constant value cannot be converted to int

怎甘沉沦 提交于 2019-12-20 02:58:19

问题


I can't see why line#5 fails to compile whereas line#4 is ok.

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)
}

回答1:


Compile-time constants are checked differently to other code, basically.

A cast of a compile-time constant into a type whose range doesn't include that value will always fail unless you explicitly have an unchecked expression. The cast is evaluated at compile time.

However, the cast of an expression which is classified as a value (rather than a constant) is evaluated at execution time, and handles overflow either with an exception (in checked code) or by truncating bits (in unchecked code).

You can see this slightly more easily using byte and just a const field vs a 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
    }
}


来源:https://stackoverflow.com/questions/29038335/constant-value-cannot-be-converted-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!