常量值不能转换为int [英] Constant value cannot be converted to int

查看:78
本文介绍了常量值不能转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不到为什么第5行无法编译而第4行正常。

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


推荐答案

基本上,对编译时常量的检查与其他代码不同。

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

强制转换除非将明确地具有 unchecked 表达式,否则将-time常量转换为不包含该值的类型的类型将始终失败。

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.

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

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 字段与一个静态只读字段:

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

这篇关于常量值不能转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆