常量值不能转换为 int [英] Constant value cannot be converted to 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
表达式.强制转换在编译时进行评估.
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
}
}
这篇关于常量值不能转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!