且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

常量值不能转换为 int

更新时间:2023-11-24 22:37:10

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

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

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

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

使用 byte 和一个 const 字段与 static readonly 字段相比,您可以更轻松地看到这一点:

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