2015-03-13 111 views
2

我看不到为什么第5行编译失败,而第4行没有问题。常量值不能转换为int

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

可能重复[C# - 恒定值“4294901760”不能转换为“廉政”( http://stackoverflow.com/questions/6027572/c-sharp-constant-value-4294901760-cannot-be-converted-to-a-int) – 2015-03-13 17:26:52

+1

@ColinCochrane它是相关的,但不是一个重复。这就解释了为什么这个值不能转换为int类型,但是这个问题是关于为什么这个错误只发生在一个常量上,而不是一个被设置为相同值的变量。 – juharr 2015-03-13 17:29:23

回答

6

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

将编译时常量强制转换为范围不包含该值的类型将始终失败,除非显式地具有unchecked表达式。该转换在编译时进行评估。

然而,其被归类为(而不是一个常数)在执行时被求值的表达式的铸造,并处理溢出或者与异常(在检查的码)或通过截断位(在未选中码)。

您可以在此稍微更容易使用byte,只是一个const场VS一个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 
    } 
}